ee5cbe1ffbef825817e23698e4e57d7748256f85
[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 gboolean     _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         gboolean has_children;
471         
472         rendobj = G_OBJECT(renderer);
473         gtk_tree_model_get (tree_model, iter,
474                             TNY_GTK_FOLDER_STORE_TREE_MODEL_TYPE_COLUMN, &type,
475                             TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN, &fname,
476                             TNY_GTK_FOLDER_STORE_TREE_MODEL_UNREAD_COLUMN, &unread,
477                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, &instance,
478                             -1);
479         has_children = gtk_tree_model_iter_has_child (tree_model, iter);
480
481         if (!fname)
482                 return;
483
484         if (!instance) {
485                 g_free (fname);
486                 return;
487         }
488
489         /* MERGE is not needed anymore as the folder now has the correct type jschmid */
490         /* We include the MERGE type here because it's used to create
491            the local OUTBOX folder */
492         if (type == TNY_FOLDER_TYPE_NORMAL || 
493             type == TNY_FOLDER_TYPE_UNKNOWN) {
494                 type = modest_tny_folder_guess_folder_type (TNY_FOLDER (instance));
495         }
496
497         switch (type) {
498         case TNY_FOLDER_TYPE_ROOT:
499                 if (TNY_IS_ACCOUNT (instance)) {
500                         
501                         if (modest_tny_account_is_virtual_local_folders (
502                                 TNY_ACCOUNT (instance))) {
503                                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_LOCAL_FOLDERS);
504                         }
505                         else {
506                                 account_id = tny_account_get_id (TNY_ACCOUNT (instance));
507                                 
508                                 if (!strcmp (account_id, MODEST_MMC_ACCOUNT_ID))
509                                         pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_MMC);
510                                 else
511                                         pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_ACCOUNT);
512                         }
513                 }
514                 break;
515         case TNY_FOLDER_TYPE_INBOX:
516             pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_INBOX);
517             break;
518         case TNY_FOLDER_TYPE_OUTBOX:
519                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_OUTBOX);
520                 break;
521         case TNY_FOLDER_TYPE_JUNK:
522                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_JUNK);
523                 break;
524         case TNY_FOLDER_TYPE_SENT:
525                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_SENT);
526                 break;
527         case TNY_FOLDER_TYPE_TRASH:
528                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_TRASH);
529                 break;
530         case TNY_FOLDER_TYPE_DRAFTS:
531                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_DRAFTS);
532                 break;
533         case TNY_FOLDER_TYPE_NORMAL:
534         default:
535                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_NORMAL);
536                 break;
537         }
538         
539         g_object_unref (G_OBJECT (instance));
540         g_free (fname);
541
542         /* Set pixbuf */
543         g_object_set (rendobj, "pixbuf", pixbuf, NULL);
544         if (has_children && (pixbuf != NULL)) {
545                 GdkPixbuf *open_pixbuf, *closed_pixbuf;
546                 GdkPixbuf *open_emblem, *closed_emblem;
547                 open_pixbuf = gdk_pixbuf_copy (pixbuf);
548                 closed_pixbuf = gdk_pixbuf_copy (pixbuf);
549                 open_emblem = modest_platform_get_icon ("qgn_list_gene_fldr_exp");
550                 closed_emblem = modest_platform_get_icon ("qgn_list_gene_fldr_clp");
551
552                 if (open_emblem) {
553                         gdk_pixbuf_composite (open_emblem, open_pixbuf, 0, 0, 
554                                               MIN (gdk_pixbuf_get_width (open_emblem), 
555                                                    gdk_pixbuf_get_width (open_pixbuf)),
556                                               MIN (gdk_pixbuf_get_height (open_emblem), 
557                                                    gdk_pixbuf_get_height (open_pixbuf)),
558                                               0, 0, 1, 1, GDK_INTERP_NEAREST, 255);
559                         g_object_set (rendobj, "pixbuf-expander-open", open_pixbuf, NULL);
560                         g_object_unref (open_emblem);
561                 }
562                 if (closed_emblem) {
563                         gdk_pixbuf_composite (closed_emblem, closed_pixbuf, 0, 0, 
564                                               MIN (gdk_pixbuf_get_width (closed_emblem), 
565                                                    gdk_pixbuf_get_width (closed_pixbuf)),
566                                               MIN (gdk_pixbuf_get_height (closed_emblem), 
567                                                    gdk_pixbuf_get_height (closed_pixbuf)),
568                                               0, 0, 1, 1, GDK_INTERP_NEAREST, 255);
569                         g_object_set (rendobj, "pixbuf-expander-closed", closed_pixbuf, NULL);
570                         g_object_unref (closed_emblem);
571                 }
572                 if (closed_pixbuf)
573                         g_object_unref (closed_pixbuf);
574                 if (open_pixbuf)
575                         g_object_unref (open_pixbuf);
576         }
577
578         if (pixbuf != NULL)
579                 g_object_unref (pixbuf);
580 }
581
582 static void
583 add_columns (GtkWidget *treeview)
584 {
585         GtkTreeViewColumn *column;
586         GtkCellRenderer *renderer;
587         GtkTreeSelection *sel;
588
589         /* Create column */
590         column = gtk_tree_view_column_new ();   
591         
592         /* Set icon and text render function */
593         renderer = gtk_cell_renderer_pixbuf_new();
594         gtk_tree_view_column_pack_start (column, renderer, FALSE);
595         gtk_tree_view_column_set_cell_data_func(column, renderer,
596                                                 icon_cell_data, treeview, NULL);
597         
598         renderer = gtk_cell_renderer_text_new();
599         gtk_tree_view_column_pack_start (column, renderer, FALSE);
600         gtk_tree_view_column_set_cell_data_func(column, renderer,
601                                                 text_cell_data, treeview, NULL);
602         
603         /* Set selection mode */
604         sel = gtk_tree_view_get_selection (GTK_TREE_VIEW(treeview));
605         gtk_tree_selection_set_mode (sel, GTK_SELECTION_SINGLE);
606
607         /* Set treeview appearance */
608         gtk_tree_view_column_set_spacing (column, 2);
609         gtk_tree_view_column_set_resizable (column, TRUE);
610         gtk_tree_view_column_set_fixed_width (column, TRUE);            
611         gtk_tree_view_set_headers_clickable (GTK_TREE_VIEW(treeview), FALSE);
612         gtk_tree_view_set_enable_search (GTK_TREE_VIEW(treeview), FALSE);
613
614         /* Add column */
615         gtk_tree_view_append_column (GTK_TREE_VIEW(treeview),column);
616 }
617
618 static void
619 modest_folder_view_init (ModestFolderView *obj)
620 {
621         ModestFolderViewPrivate *priv;
622         ModestConf *conf;
623         
624         priv =  MODEST_FOLDER_VIEW_GET_PRIVATE(obj);
625         
626         priv->timer_expander = 0;
627         priv->account_store  = NULL;
628         priv->query          = NULL;
629         priv->style          = MODEST_FOLDER_VIEW_STYLE_SHOW_ALL;
630         priv->cur_folder_store   = NULL;
631         priv->visible_account_id = NULL;
632
633         /* Initialize the local account name */
634         conf = modest_runtime_get_conf();
635         priv->local_account_name = modest_conf_get_string (conf, MODEST_CONF_DEVICE_NAME, NULL);
636
637         /* Init email clipboard */
638         priv->clipboard = modest_runtime_get_email_clipboard ();
639         priv->hidding_ids = NULL;
640         priv->n_selected = 0;
641         priv->reselect = FALSE;
642
643         /* Build treeview */
644         add_columns (GTK_WIDGET (obj));
645
646         /* Setup drag and drop */
647         setup_drag_and_drop (GTK_TREE_VIEW(obj));
648
649         /* Connect signals */
650         g_signal_connect (G_OBJECT (obj), 
651                           "key-press-event", 
652                           G_CALLBACK (on_key_pressed), NULL);
653
654         /*
655          * Track changes in the local account name (in the device it
656          * will be the device name)
657          */
658         priv->conf_key_signal = 
659                 g_signal_connect (G_OBJECT(conf), 
660                                   "key_changed",
661                                   G_CALLBACK(on_configuration_key_changed), obj);
662 }
663
664 static void
665 tny_account_store_view_init (gpointer g, gpointer iface_data)
666 {
667         TnyAccountStoreViewIface *klass = (TnyAccountStoreViewIface *)g;
668
669         klass->set_account_store_func = modest_folder_view_set_account_store;
670
671         return;
672 }
673
674 static void
675 modest_folder_view_finalize (GObject *obj)
676 {
677         ModestFolderViewPrivate *priv;
678         GtkTreeSelection    *sel;
679         
680         g_return_if_fail (obj);
681         
682         priv =  MODEST_FOLDER_VIEW_GET_PRIVATE(obj);
683
684         if (priv->timer_expander != 0) {
685                 g_source_remove (priv->timer_expander);
686                 priv->timer_expander = 0;
687         }
688
689         if (priv->account_store) {
690                 g_signal_handler_disconnect (G_OBJECT(priv->account_store),
691                                              priv->account_update_signal);
692                 g_signal_handler_disconnect (G_OBJECT(priv->account_store),
693                                              priv->accounts_reloaded_signal);
694                 g_signal_handler_disconnect (G_OBJECT(priv->account_store),
695                                              priv->account_removed_signal);
696                 g_object_unref (G_OBJECT(priv->account_store));
697                 priv->account_store = NULL;
698         }
699
700         if (priv->query) {
701                 g_object_unref (G_OBJECT (priv->query));
702                 priv->query = NULL;
703         }
704
705         sel = gtk_tree_view_get_selection (GTK_TREE_VIEW(obj));
706         if (sel)
707                 g_signal_handler_disconnect (G_OBJECT(sel), priv->changed_signal);
708
709         g_free (priv->local_account_name);
710         g_free (priv->visible_account_id);
711         
712         if (priv->conf_key_signal) {
713                 g_signal_handler_disconnect (modest_runtime_get_conf (),
714                                              priv->conf_key_signal);
715                 priv->conf_key_signal = 0;
716         }
717
718         if (priv->cur_folder_store) {
719                 if (TNY_IS_FOLDER(priv->cur_folder_store))
720                         tny_folder_sync (TNY_FOLDER(priv->cur_folder_store), FALSE, NULL);
721                         /* FALSE --> expunge the message */
722
723                 g_object_unref (priv->cur_folder_store);
724                 priv->cur_folder_store = NULL;
725         }
726
727         /* Clear hidding array created by cut operation */
728         _clear_hidding_filter (MODEST_FOLDER_VIEW (obj));
729
730         G_OBJECT_CLASS(parent_class)->finalize (obj);
731 }
732
733
734 static void
735 modest_folder_view_set_account_store (TnyAccountStoreView *self, TnyAccountStore *account_store)
736 {
737         ModestFolderViewPrivate *priv;
738         TnyDevice *device;
739
740         g_return_if_fail (MODEST_IS_FOLDER_VIEW (self));
741         g_return_if_fail (TNY_IS_ACCOUNT_STORE (account_store));
742
743         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (self);
744         device = tny_account_store_get_device (account_store);
745
746         if (G_UNLIKELY (priv->account_store)) {
747
748                 if (g_signal_handler_is_connected (G_OBJECT (priv->account_store), 
749                                                    priv->account_update_signal))
750                         g_signal_handler_disconnect (G_OBJECT (priv->account_store), 
751                                                      priv->account_update_signal);
752                 if (g_signal_handler_is_connected (G_OBJECT (priv->account_store), 
753                                                    priv->accounts_reloaded_signal))
754                         g_signal_handler_disconnect (G_OBJECT (priv->account_store), 
755                                                      priv->accounts_reloaded_signal);
756                 if (g_signal_handler_is_connected (G_OBJECT (priv->account_store), 
757                                                    priv->account_removed_signal))
758                         g_signal_handler_disconnect (G_OBJECT (priv->account_store), 
759                                                      priv->account_removed_signal);
760
761                 g_object_unref (G_OBJECT (priv->account_store));
762         }
763
764         priv->account_store = g_object_ref (G_OBJECT (account_store));
765
766         priv->account_update_signal = 
767                 g_signal_connect (G_OBJECT(account_store), "account_update",
768                                   G_CALLBACK (on_account_update), self);
769
770         priv->account_removed_signal = 
771                 g_signal_connect (G_OBJECT(account_store), "account_removed",
772                                   G_CALLBACK (on_account_removed), self);
773
774         priv->accounts_reloaded_signal = 
775                 g_signal_connect (G_OBJECT(account_store), "accounts_reloaded",
776                                   G_CALLBACK (on_accounts_reloaded), self);
777
778         g_signal_connect (G_OBJECT(account_store), "connecting_finished",
779                                 G_CALLBACK (on_accounts_reloaded), self);
780
781         on_accounts_reloaded (account_store, (gpointer ) self);
782         
783         g_object_unref (G_OBJECT (device));
784 }
785
786 static void
787 on_account_removed (TnyAccountStore *account_store, 
788                     TnyAccount *account,
789                     gpointer user_data)
790 {
791         ModestFolderView *self = MODEST_FOLDER_VIEW (user_data);
792         ModestFolderViewPrivate *priv;
793
794         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (self);
795
796         /* If the removed account is the currently viewed one then
797            clear the configuration value. The new visible account will be the default account */
798         if (!strcmp (priv->visible_account_id, tny_account_get_id (account))) {
799                 modest_folder_view_set_account_id_of_visible_server_account (self, NULL);
800         }
801 }
802
803 static void
804 on_account_update (TnyAccountStore *account_store, 
805                    const gchar *account,
806                    gpointer user_data)
807 {
808         ModestFolderView *self = NULL;
809         ModestFolderViewPrivate *priv;
810
811         g_return_if_fail (MODEST_IS_FOLDER_VIEW (user_data));
812         self = MODEST_FOLDER_VIEW (user_data);
813         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (self);
814
815         if (!priv->visible_account_id)
816                 modest_widget_memory_restore (modest_runtime_get_conf(), G_OBJECT(self),
817                                               MODEST_CONF_FOLDER_VIEW_KEY);
818
819         if (!modest_folder_view_update_model (self, account_store))
820                 g_printerr ("modest: failed to update model for changes in '%s'",
821                             account);
822 }
823
824 static void 
825 on_accounts_reloaded   (TnyAccountStore *account_store, 
826                         gpointer user_data)
827 {
828         g_return_if_fail (MODEST_IS_FOLDER_VIEW (user_data));
829         modest_folder_view_update_model (MODEST_FOLDER_VIEW (user_data), account_store);
830 }
831
832 void
833 modest_folder_view_set_title (ModestFolderView *self, const gchar *title)
834 {
835         GtkTreeViewColumn *col;
836         
837         g_return_if_fail (self);
838
839         col = gtk_tree_view_get_column (GTK_TREE_VIEW(self), 0);
840         if (!col) {
841                 g_printerr ("modest: failed get column for title\n");
842                 return;
843         }
844
845         gtk_tree_view_column_set_title (col, title);
846         gtk_tree_view_set_headers_visible (GTK_TREE_VIEW(self),
847                                            title != NULL);
848 }
849
850 static gboolean
851 modest_folder_view_on_map (ModestFolderView *self, 
852                            GdkEventExpose *event,
853                            gpointer data)
854 {
855         ModestFolderViewPrivate *priv;
856
857         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (self);
858
859         /* This won't happen often */
860         if (G_UNLIKELY (priv->reselect)) {
861                 /* Select the first inbox or the local account if not found */
862
863                 /* TODO: this could cause a lock at startup, so we
864                    comment it for the moment. We know that this will
865                    be a bug, because the INBOX is not selected, but we
866                    need to rewrite some parts of Modest to avoid the
867                    deathlock situation */
868 /*              modest_folder_view_select_first_inbox_or_local (self); */
869                 priv->reselect = FALSE;
870         }
871         return FALSE;
872 }
873
874 GtkWidget*
875 modest_folder_view_new (TnyFolderStoreQuery *query)
876 {
877         GObject *self;
878         ModestFolderViewPrivate *priv;
879         GtkTreeSelection *sel;
880         
881         self = G_OBJECT (g_object_new (MODEST_TYPE_FOLDER_VIEW, NULL));
882         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (self);
883
884         if (query)
885                 priv->query = g_object_ref (query);
886         
887         sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(self));
888         priv->changed_signal = g_signal_connect (sel, "changed",
889                                                  G_CALLBACK (on_selection_changed), self);
890
891         g_signal_connect (self, "expose-event", G_CALLBACK (modest_folder_view_on_map), NULL);
892
893         return GTK_WIDGET(self);
894 }
895
896 /* this feels dirty; any other way to expand all the root items? */
897 static void
898 expand_root_items (ModestFolderView *self)
899 {
900         GtkTreePath *path;
901         path = gtk_tree_path_new_first ();
902
903         /* all folders should have child items, so.. */
904         while (gtk_tree_view_expand_row (GTK_TREE_VIEW(self), path, FALSE))
905                 gtk_tree_path_next (path);
906         
907         gtk_tree_path_free (path);
908 }
909
910 /*
911  * We use this function to implement the
912  * MODEST_FOLDER_VIEW_STYLE_SHOW_ONE style. We only show the default
913  * account in this case, and the local folders.
914  */
915 static gboolean 
916 filter_row (GtkTreeModel *model,
917             GtkTreeIter *iter,
918             gpointer data)
919 {
920         ModestFolderViewPrivate *priv;
921         gboolean retval = TRUE;
922         TnyFolderType type = TNY_FOLDER_TYPE_UNKNOWN;
923         GObject *instance = NULL;
924         const gchar *id = NULL;
925         guint i;
926         gboolean found = FALSE;
927         gboolean cleared = FALSE;
928         
929         g_return_val_if_fail (MODEST_IS_FOLDER_VIEW (data), FALSE);
930         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (data);
931
932         gtk_tree_model_get (model, iter,
933                             TNY_GTK_FOLDER_STORE_TREE_MODEL_TYPE_COLUMN, &type,
934                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, &instance,
935                             -1);
936
937         /* Do not show if there is no instance, this could indeed
938            happen when the model is being modified while it's being
939            drawn. This could occur for example when moving folders
940            using drag&drop */
941         if (!instance)
942                 return FALSE;
943
944         if (type == TNY_FOLDER_TYPE_ROOT) {
945                 /* TNY_FOLDER_TYPE_ROOT means that the instance is an
946                    account instead of a folder. */
947                 if (TNY_IS_ACCOUNT (instance)) {
948                         TnyAccount *acc = TNY_ACCOUNT (instance);
949                         const gchar *account_id = tny_account_get_id (acc);
950         
951                         /* If it isn't a special folder, 
952                          * don't show it unless it is the visible account: */
953                         if (!modest_tny_account_is_virtual_local_folders (acc) &&
954                                 strcmp (account_id, MODEST_MMC_ACCOUNT_ID)) { 
955                                 /* Show only the visible account id */
956                                 if (priv->visible_account_id && strcmp (account_id, priv->visible_account_id))
957                                         retval = FALSE;
958                         }
959                         
960                         /* Never show these to the user. They are merged into one folder 
961                          * in the local-folders account instead: */
962                         if (retval && MODEST_IS_TNY_OUTBOX_ACCOUNT (acc))
963                                 retval = FALSE;
964                 }
965         }
966         
967         /* The virtual local-folders folder store is also shown by default. */
968
969         /* Check hiding (if necessary) */
970         cleared = modest_email_clipboard_cleared (priv->clipboard);            
971         if ((retval) && (!cleared) && (TNY_IS_FOLDER (instance))) {
972                 id = tny_folder_get_id (TNY_FOLDER(instance));
973                 if (priv->hidding_ids != NULL)
974                         for (i=0; i < priv->n_selected && !found; i++)
975                                 if (priv->hidding_ids[i] != NULL && id != NULL)
976                                         found = (!strcmp (priv->hidding_ids[i], id));
977                 
978                 retval = !found;
979         }
980
981         /* Free */
982         g_object_unref (instance);
983
984         return retval;
985 }
986
987 gboolean
988 modest_folder_view_update_model (ModestFolderView *self,
989                                  TnyAccountStore *account_store)
990 {
991         ModestFolderViewPrivate *priv;
992         GtkTreeModel *model /* , *old_model */;
993         /* TnyAccount *local_account; */
994         TnyList *model_as_list;
995
996         g_return_val_if_fail (MODEST_IS_FOLDER_VIEW (self), FALSE);
997         g_return_val_if_fail (account_store, FALSE);
998
999         priv =  MODEST_FOLDER_VIEW_GET_PRIVATE(self);
1000         
1001         /* Notify that there is no folder selected */
1002         g_signal_emit (G_OBJECT(self), 
1003                        signals[FOLDER_SELECTION_CHANGED_SIGNAL], 0,
1004                        NULL, FALSE);
1005         if (priv->cur_folder_store) {
1006                 g_object_unref (priv->cur_folder_store);
1007                 priv->cur_folder_store = NULL;
1008         }
1009
1010         /* FIXME: the local accounts are not shown when the query
1011            selects only the subscribed folders. */
1012 /*      model        = tny_gtk_folder_store_tree_model_new (TRUE, priv->query); */
1013         model        = tny_gtk_folder_store_tree_model_new (TRUE, NULL);
1014         
1015         /* Deal with the model via its TnyList Interface,
1016          * filling the TnyList via a get_accounts() call: */
1017         model_as_list = TNY_LIST(model);
1018
1019         /* Get the accounts: */
1020         tny_account_store_get_accounts (TNY_ACCOUNT_STORE(account_store),
1021                                         model_as_list,
1022                                         TNY_ACCOUNT_STORE_STORE_ACCOUNTS);
1023         g_object_unref (model_as_list);
1024         model_as_list = NULL;   
1025                                                      
1026         GtkTreeModel *filter_model = NULL, *sortable = NULL;
1027
1028         sortable = gtk_tree_model_sort_new_with_model (model);
1029         gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE(sortable),
1030                                               TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN, 
1031                                               GTK_SORT_ASCENDING);
1032         gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (sortable),
1033                                          TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN,
1034                                          cmp_rows, NULL, NULL);
1035
1036         /* Create filter model */
1037         filter_model = gtk_tree_model_filter_new (sortable, NULL);
1038         gtk_tree_model_filter_set_visible_func (GTK_TREE_MODEL_FILTER (filter_model),
1039                                                 filter_row,
1040                                                 self,
1041                                                 NULL);
1042 /*      if (priv->style == MODEST_FOLDER_VIEW_STYLE_SHOW_ONE) { */
1043 /*              filter_model = gtk_tree_model_filter_new (sortable, NULL); */
1044 /*              gtk_tree_model_filter_set_visible_func (GTK_TREE_MODEL_FILTER (filter_model), */
1045 /*                                                      filter_row, */
1046 /*                                                      self, */
1047 /*                                                      NULL); */
1048 /*      } */
1049
1050         /* Set new model */
1051         gtk_tree_view_set_model (GTK_TREE_VIEW(self), filter_model);
1052 /*      gtk_tree_view_set_model (GTK_TREE_VIEW(self),  */
1053 /*                               (filter_model) ? filter_model : sortable); */
1054
1055         g_object_unref (model);
1056         g_object_unref (filter_model);
1057 /*      if (filter_model) */
1058 /*              g_object_unref (filter_model); */
1059                         
1060         g_object_unref (sortable);
1061
1062         /* Force a reselection of the INBOX next time the widget is shown */
1063         priv->reselect = TRUE;
1064                         
1065         return TRUE;
1066 }
1067
1068
1069 static void
1070 on_selection_changed (GtkTreeSelection *sel, gpointer user_data)
1071 {
1072         GtkTreeModel            *model;
1073         TnyFolderStore          *folder = NULL;
1074         GtkTreeIter             iter;
1075         ModestFolderView        *tree_view;
1076         ModestFolderViewPrivate *priv;
1077
1078         g_return_if_fail (sel);
1079         g_return_if_fail (user_data);
1080         
1081         priv = MODEST_FOLDER_VIEW_GET_PRIVATE(user_data);
1082
1083         if(!gtk_tree_selection_get_selected (sel, &model, &iter))
1084                 return;
1085
1086         /* Notify the display name observers */
1087         g_signal_emit (G_OBJECT(user_data),
1088                        signals[FOLDER_DISPLAY_NAME_CHANGED_SIGNAL], 0,
1089                        NULL);
1090
1091         tree_view = MODEST_FOLDER_VIEW (user_data);
1092         gtk_tree_model_get (model, &iter,
1093                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, &folder,
1094                             -1);
1095
1096         /* If the folder is the same do not notify */
1097         if (priv->cur_folder_store == folder && folder) {
1098                 g_object_unref (folder);
1099                 return;
1100         }
1101         
1102         /* Current folder was unselected */
1103         if (priv->cur_folder_store) {
1104                 if (TNY_IS_FOLDER(priv->cur_folder_store))
1105                         tny_folder_sync (TNY_FOLDER(priv->cur_folder_store), FALSE, NULL);
1106                 /* FALSE --> don't expunge the messages */
1107
1108                 g_signal_emit (G_OBJECT(tree_view), signals[FOLDER_SELECTION_CHANGED_SIGNAL], 0,
1109                                priv->cur_folder_store, FALSE);
1110                 g_object_unref (priv->cur_folder_store);
1111                 priv->cur_folder_store = NULL;
1112         }
1113
1114         /* New current references */
1115         priv->cur_folder_store = folder;
1116
1117         /* New folder has been selected */
1118         g_signal_emit (G_OBJECT(tree_view),
1119                        signals[FOLDER_SELECTION_CHANGED_SIGNAL],
1120                        0, priv->cur_folder_store, TRUE);
1121 }
1122
1123 TnyFolderStore *
1124 modest_folder_view_get_selected (ModestFolderView *self)
1125 {
1126         ModestFolderViewPrivate *priv;
1127
1128         g_return_val_if_fail (self, NULL);
1129         
1130         priv = MODEST_FOLDER_VIEW_GET_PRIVATE(self);
1131         if (priv->cur_folder_store)
1132                 g_object_ref (priv->cur_folder_store);
1133
1134         return priv->cur_folder_store;
1135 }
1136
1137 static gint
1138 get_cmp_rows_type_pos (GObject *folder)
1139 {
1140         /* Remote accounts -> Local account -> MMC account .*/
1141         /* 0, 1, 2 */
1142         
1143         if (TNY_IS_ACCOUNT (folder) && 
1144                 modest_tny_account_is_virtual_local_folders (
1145                         TNY_ACCOUNT (folder))) {
1146                 return 1;
1147         } else if (TNY_IS_ACCOUNT (folder)) {
1148                 TnyAccount *account = TNY_ACCOUNT (folder);
1149                 const gchar *account_id = tny_account_get_id (account);
1150                 if (!strcmp (account_id, MODEST_MMC_ACCOUNT_ID))
1151                         return 2;
1152                 else
1153                         return 0;
1154         }
1155         else {
1156                 printf ("DEBUG: %s: unexpected type.\n", __FUNCTION__);
1157                 return -1; /* Should never happen */
1158         }
1159 }
1160
1161 static gint
1162 get_cmp_subfolder_type_pos (TnyFolderType t)
1163 {
1164         /* Outbox, Drafts, Sent, User */
1165         /* 0, 1, 2, 3 */
1166
1167         switch (t) {
1168         case TNY_FOLDER_TYPE_OUTBOX:
1169                 return 0;
1170                 break;
1171         case TNY_FOLDER_TYPE_DRAFTS:
1172                 return 1;
1173                 break;
1174         case TNY_FOLDER_TYPE_SENT:
1175                 return 2;
1176                 break;
1177         default:
1178                 return 3;
1179         }
1180 }
1181
1182 /*
1183  * This function orders the mail accounts according to these rules:
1184  * 1st - remote accounts
1185  * 2nd - local account
1186  * 3rd - MMC account
1187  */
1188 static gint
1189 cmp_rows (GtkTreeModel *tree_model, GtkTreeIter *iter1, GtkTreeIter *iter2,
1190           gpointer user_data)
1191 {
1192         gint cmp;
1193         gchar *name1 = NULL;
1194         gchar *name2 = NULL;
1195         TnyFolderType type = TNY_FOLDER_TYPE_UNKNOWN;
1196         TnyFolderType type2 = TNY_FOLDER_TYPE_UNKNOWN;
1197         GObject *folder1 = NULL;
1198         GObject *folder2 = NULL;
1199
1200         gtk_tree_model_get (tree_model, iter1,
1201                             TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN, &name1,
1202                             TNY_GTK_FOLDER_STORE_TREE_MODEL_TYPE_COLUMN, &type,
1203                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, &folder1,
1204                             -1);
1205         gtk_tree_model_get (tree_model, iter2,
1206                             TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN, &name2,
1207                             TNY_GTK_FOLDER_STORE_TREE_MODEL_TYPE_COLUMN, &type2,
1208                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, &folder2,
1209                             -1);
1210
1211         /* Return if we get no folder. This could happen when folder
1212            operations are happening. The model is updated after the
1213            folder copy/move actually occurs, so there could be
1214            situations where the model to be drawn is not correct */
1215         if (!folder1 || !folder2)
1216                 return 0;
1217
1218         if (type == TNY_FOLDER_TYPE_ROOT) {
1219                 /* Compare the types, so that 
1220                  * Remote accounts -> Local account -> MMC account .*/
1221                 const gint pos1 = get_cmp_rows_type_pos (folder1);
1222                 const gint pos2 = get_cmp_rows_type_pos (folder2);
1223                 /* printf ("DEBUG: %s:\n  type1=%s, pos1=%d\n  type2=%s, pos2=%d\n", 
1224                         __FUNCTION__, G_OBJECT_TYPE_NAME(folder1), pos1, G_OBJECT_TYPE_NAME(folder2), pos2); */
1225                 if (pos1 <  pos2)
1226                         cmp = -1;
1227                 else if (pos1 > pos2)
1228                         cmp = 1;
1229                 else {
1230                         /* Compare items of the same type: */
1231                         
1232                         TnyAccount *account1 = NULL;
1233                         if (TNY_IS_ACCOUNT (folder1))
1234                                 account1 = TNY_ACCOUNT (folder1);
1235                                 
1236                         TnyAccount *account2 = NULL;
1237                         if (TNY_IS_ACCOUNT (folder2))
1238                                 account2 = TNY_ACCOUNT (folder2);
1239                                 
1240                         const gchar *account_id = account1 ? tny_account_get_id (account1) : NULL;
1241                         const gchar *account_id2 = account2 ? tny_account_get_id (account2) : NULL;
1242         
1243                         if (!account_id && !account_id2)
1244                                 return 0;
1245                         else if (!account_id)
1246                                 return -1;
1247                         else if (!account_id2)
1248                                 return +1;
1249                         else if (!strcmp (account_id, MODEST_MMC_ACCOUNT_ID))
1250                                 cmp = +1;
1251                         else
1252                                 cmp = modest_text_utils_utf8_strcmp (name1, name2, TRUE);
1253                 }
1254         } else {
1255                 GtkTreeIter parent;
1256                 gboolean has_parent;
1257                 gint cmp1 = 0, cmp2 = 0;
1258                 /* get the parent to know if it's a local folder */
1259                 has_parent = gtk_tree_model_iter_parent (tree_model, &parent, iter1);
1260                 if (has_parent) {
1261                         GObject *parent_folder;
1262                         TnyFolderType parent_type = TNY_FOLDER_TYPE_UNKNOWN;
1263                         gtk_tree_model_get (tree_model, &parent, 
1264                                             TNY_GTK_FOLDER_STORE_TREE_MODEL_TYPE_COLUMN, &parent_type,
1265                                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, &parent_folder,
1266                                             -1);
1267                         if ((parent_type == TNY_FOLDER_TYPE_ROOT) &&
1268                             TNY_IS_ACCOUNT (parent_folder) &&
1269                             modest_tny_account_is_virtual_local_folders (TNY_ACCOUNT (parent_folder))) {
1270                                 cmp1 = get_cmp_subfolder_type_pos (modest_tny_folder_get_local_folder_type (TNY_FOLDER (folder1)));
1271                                 cmp2 = get_cmp_subfolder_type_pos (modest_tny_folder_get_local_folder_type (TNY_FOLDER (folder2)));
1272                         }
1273                         g_object_unref (parent_folder);
1274                 }
1275                 if (cmp1 == cmp2)
1276                         cmp = modest_text_utils_utf8_strcmp (name1, name2, TRUE);
1277                 else 
1278                         cmp = (cmp1 - cmp2);
1279         }
1280         
1281         if (folder1)
1282                 g_object_unref(G_OBJECT(folder1));
1283         if (folder2)
1284                 g_object_unref(G_OBJECT(folder2));
1285
1286         g_free (name1);
1287         g_free (name2);
1288
1289         return cmp;     
1290 }
1291
1292 /*****************************************************************************/
1293 /*                        DRAG and DROP stuff                                */
1294 /*****************************************************************************/
1295
1296 /*
1297  * This function fills the #GtkSelectionData with the row and the
1298  * model that has been dragged. It's called when this widget is a
1299  * source for dnd after the event drop happened
1300  */
1301 static void
1302 on_drag_data_get (GtkWidget *widget, 
1303                   GdkDragContext *context, 
1304                   GtkSelectionData *selection_data, 
1305                   guint info, 
1306                   guint time, 
1307                   gpointer data)
1308 {
1309         GtkTreeSelection *selection;
1310         GtkTreeModel *model;
1311         GtkTreeIter iter;
1312         GtkTreePath *source_row;
1313
1314         selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (widget));
1315         gtk_tree_selection_get_selected (selection, &model, &iter);
1316         source_row = gtk_tree_model_get_path (model, &iter);
1317
1318         gtk_tree_set_row_drag_data (selection_data,
1319                                     model,
1320                                     source_row);
1321
1322         gtk_tree_path_free (source_row);
1323 }
1324
1325 typedef struct _DndHelper {
1326         gboolean delete_source;
1327         GtkTreePath *source_row;
1328         GdkDragContext *context;
1329         guint time;
1330 } DndHelper;
1331
1332
1333 /*
1334  * This function is the callback of the
1335  * modest_mail_operation_xfer_msgs () and
1336  * modest_mail_operation_xfer_folder() calls. We check here if the
1337  * message/folder was correctly asynchronously transferred. The reason
1338  * to use the same callback is that the code is the same, it only has
1339  * to check that the operation went fine and then finalize the drag
1340  * and drop action
1341  */
1342 static void
1343 on_progress_changed (ModestMailOperation *mail_op, 
1344                      ModestMailOperationState *state,
1345                      gpointer user_data)
1346 {
1347         gboolean success;
1348         DndHelper *helper;
1349
1350         helper = (DndHelper *) user_data;
1351
1352         if (!state->finished)
1353                 return;
1354
1355         if (state->status == MODEST_MAIL_OPERATION_STATUS_SUCCESS) {
1356                 success = TRUE;
1357         } else {
1358                 success = FALSE;
1359         }
1360
1361         /* Notify the drag source. Never call delete, the monitor will
1362            do the job if needed */
1363         gtk_drag_finish (helper->context, success, FALSE, helper->time);
1364
1365         /* Free the helper */
1366         gtk_tree_path_free (helper->source_row);        
1367         g_slice_free (DndHelper, helper);
1368 }
1369
1370 /*
1371  * This function is used by drag_data_received_cb to manage drag and
1372  * drop of a header, i.e, and drag from the header view to the folder
1373  * view.
1374  */
1375 static void
1376 drag_and_drop_from_header_view (GtkTreeModel *source_model,
1377                                 GtkTreeModel *dest_model,
1378                                 GtkTreePath  *dest_row,
1379                                 DndHelper    *helper)
1380 {
1381         TnyList *headers = NULL;
1382         TnyHeader *header = NULL;
1383         TnyFolder *folder = NULL;
1384         ModestMailOperation *mail_op = NULL;
1385         GtkTreeIter source_iter, dest_iter;
1386
1387         g_return_if_fail (GTK_IS_TREE_MODEL(source_model));
1388         g_return_if_fail (GTK_IS_TREE_MODEL(dest_model));
1389         g_return_if_fail (dest_row);
1390         g_return_if_fail (helper);
1391         
1392         /* Get header */
1393         gtk_tree_model_get_iter (source_model, &source_iter, helper->source_row);
1394         gtk_tree_model_get (source_model, &source_iter, 
1395                             TNY_GTK_HEADER_LIST_MODEL_INSTANCE_COLUMN, 
1396                             &header, -1);
1397         if (!TNY_IS_HEADER(header)) {
1398                 g_warning ("BUG: %s could not get a valid header", __FUNCTION__);
1399                 goto cleanup;
1400         }
1401         
1402         /* Get Folder */
1403         gtk_tree_model_get_iter (dest_model, &dest_iter, dest_row);
1404         gtk_tree_model_get (dest_model, &dest_iter, 
1405                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, 
1406                             &folder, -1);
1407
1408         if (!TNY_IS_FOLDER(folder)) {
1409                 g_warning ("BUG: %s could not get a valid folder", __FUNCTION__);
1410                 goto cleanup;
1411         }
1412
1413         /* Transfer message */
1414         mail_op = modest_mail_operation_new (MODEST_MAIL_OPERATION_TYPE_RECEIVE, NULL);
1415         modest_mail_operation_queue_add (modest_runtime_get_mail_operation_queue (),
1416                                          mail_op);
1417         g_signal_connect (G_OBJECT (mail_op), "progress-changed",
1418                           G_CALLBACK (on_progress_changed), helper);
1419
1420         headers = tny_simple_list_new ();
1421         tny_list_append (headers, G_OBJECT (header));
1422         modest_mail_operation_xfer_msgs (mail_op, 
1423                                          headers, 
1424                                          folder, 
1425                                          helper->delete_source, 
1426                                          NULL, NULL);
1427         
1428         /* Frees */
1429 cleanup:
1430         if (G_IS_OBJECT(mail_op))
1431                 g_object_unref (G_OBJECT (mail_op));
1432         if (G_IS_OBJECT(header))
1433                 g_object_unref (G_OBJECT (header));
1434         if (G_IS_OBJECT(folder))
1435                 g_object_unref (G_OBJECT (folder));
1436         if (G_IS_OBJECT(headers))
1437                 g_object_unref (headers);
1438 }
1439
1440 /*
1441  * This function is used by drag_data_received_cb to manage drag and
1442  * drop of a folder, i.e, and drag from the folder view to the same
1443  * folder view.
1444  */
1445 static void
1446 drag_and_drop_from_folder_view (GtkTreeModel     *source_model,
1447                                 GtkTreeModel     *dest_model,
1448                                 GtkTreePath      *dest_row,
1449                                 GtkSelectionData *selection_data,
1450                                 DndHelper        *helper)
1451 {
1452         ModestMailOperation *mail_op = NULL;
1453         GtkTreeIter parent_iter, iter;
1454         TnyFolderStore *parent_folder = NULL;
1455         TnyFolder *folder = NULL;
1456
1457         /* Check if the drag is possible */
1458 /*      if (!gtk_tree_path_compare (helper->source_row, dest_row) || */
1459 /*          !gtk_tree_drag_dest_row_drop_possible (GTK_TREE_DRAG_DEST (dest_model), */
1460 /*                                                 dest_row, */
1461 /*                                                 selection_data)) { */
1462         if (!gtk_tree_path_compare (helper->source_row, dest_row)) {
1463
1464                 gtk_drag_finish (helper->context, FALSE, FALSE, helper->time);
1465                 gtk_tree_path_free (helper->source_row);        
1466                 g_slice_free (DndHelper, helper);
1467                 return;
1468         }
1469
1470         /* Get data */
1471         gtk_tree_model_get_iter (source_model, &parent_iter, dest_row);
1472         gtk_tree_model_get_iter (source_model, &iter, helper->source_row);
1473         gtk_tree_model_get (source_model, &parent_iter, 
1474                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, 
1475                             &parent_folder, -1);
1476         gtk_tree_model_get (source_model, &iter,
1477                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN,
1478                             &folder, -1);
1479
1480         /* Offer the connection dialog if necessary, for the destination parent folder and source folder: */
1481         if (modest_platform_connect_and_wait_if_network_folderstore (NULL, parent_folder) && 
1482                 modest_platform_connect_and_wait_if_network_folderstore (NULL, TNY_FOLDER_STORE (folder))) {
1483                 /* Do the mail operation */
1484                 mail_op = modest_mail_operation_new_with_error_handling (MODEST_MAIL_OPERATION_TYPE_RECEIVE, 
1485                                                                  NULL,
1486                                                                  modest_ui_actions_move_folder_error_handler,
1487                                                                  NULL);
1488                 modest_mail_operation_queue_add (modest_runtime_get_mail_operation_queue (), 
1489                                          mail_op);
1490                 g_signal_connect (G_OBJECT (mail_op), "progress-changed",
1491                                   G_CALLBACK (on_progress_changed), helper);
1492
1493                 modest_mail_operation_xfer_folder (mail_op, 
1494                                            folder, 
1495                                            parent_folder,
1496                                            helper->delete_source,
1497                                            NULL,
1498                                            NULL);
1499         }
1500         
1501         /* Frees */
1502         g_object_unref (G_OBJECT (parent_folder));
1503         g_object_unref (G_OBJECT (folder));
1504         g_object_unref (G_OBJECT (mail_op));
1505 }
1506
1507 /*
1508  * This function receives the data set by the "drag-data-get" signal
1509  * handler. This information comes within the #GtkSelectionData. This
1510  * function will manage both the drags of folders of the treeview and
1511  * drags of headers of the header view widget.
1512  */
1513 static void 
1514 on_drag_data_received (GtkWidget *widget, 
1515                        GdkDragContext *context, 
1516                        gint x, 
1517                        gint y, 
1518                        GtkSelectionData *selection_data, 
1519                        guint target_type, 
1520                        guint time, 
1521                        gpointer data)
1522 {
1523         GtkWidget *source_widget;
1524         GtkTreeModel *dest_model, *source_model;
1525         GtkTreePath *source_row, *dest_row;
1526         GtkTreeViewDropPosition pos;
1527         gboolean success = FALSE, delete_source = FALSE;
1528         DndHelper *helper = NULL; 
1529
1530         /* Do not allow further process */
1531         g_signal_stop_emission_by_name (widget, "drag-data-received");
1532         source_widget = gtk_drag_get_source_widget (context);
1533
1534         /* Get the action */
1535         if (context->action == GDK_ACTION_MOVE) {
1536                 delete_source = TRUE;
1537
1538                 /* Notify that there is no folder selected. We need to
1539                    do this in order to update the headers view (and
1540                    its monitors, because when moving, the old folder
1541                    won't longer exist. We can not wait for the end of
1542                    the operation, because the operation won't start if
1543                    the folder is in use */
1544                 if (source_widget == widget) {
1545                         ModestFolderViewPrivate *priv;
1546
1547                         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (widget);
1548                         if (priv->cur_folder_store) {
1549                                 g_object_unref (priv->cur_folder_store);
1550                                 priv->cur_folder_store = NULL;
1551                         }
1552
1553                         g_signal_emit (G_OBJECT (widget), 
1554                                        signals[FOLDER_SELECTION_CHANGED_SIGNAL], 0, NULL, FALSE);
1555                 }
1556         }
1557
1558         /* Check if the get_data failed */
1559         if (selection_data == NULL || selection_data->length < 0)
1560                 gtk_drag_finish (context, success, FALSE, time);
1561
1562         /* Get the models */
1563         gtk_tree_get_row_drag_data (selection_data,
1564                                     &source_model,
1565                                     &source_row);
1566
1567         /* Select the destination model */
1568         if (source_widget == widget) {
1569                 dest_model = source_model;
1570         } else {
1571                 dest_model = gtk_tree_view_get_model (GTK_TREE_VIEW (widget));
1572         }
1573
1574         /* Get the path to the destination row. Can not call
1575            gtk_tree_view_get_drag_dest_row() because the source row
1576            is not selected anymore */
1577         gtk_tree_view_get_dest_row_at_pos (GTK_TREE_VIEW (widget), x, y,
1578                                            &dest_row, &pos);
1579
1580         /* Only allow drops IN other rows */
1581         if (!dest_row || pos == GTK_TREE_VIEW_DROP_BEFORE || pos == GTK_TREE_VIEW_DROP_AFTER)
1582                 gtk_drag_finish (context, success, FALSE, time);
1583
1584         /* Create the helper */
1585         helper = g_slice_new0 (DndHelper);
1586         helper->delete_source = delete_source;
1587         helper->source_row = gtk_tree_path_copy (source_row);
1588         helper->context = context;
1589         helper->time = time;
1590
1591         /* Drags from the header view */
1592         if (source_widget != widget) {
1593
1594                 drag_and_drop_from_header_view (source_model,
1595                                                 dest_model,
1596                                                 dest_row,
1597                                                 helper);
1598         } else {
1599
1600
1601                 drag_and_drop_from_folder_view (source_model,
1602                                                 dest_model,
1603                                                 dest_row,
1604                                                 selection_data, 
1605                                                 helper);
1606         }
1607
1608         /* Frees */
1609         gtk_tree_path_free (source_row);
1610         gtk_tree_path_free (dest_row);
1611 }
1612
1613 /*
1614  * We define a "drag-drop" signal handler because we do not want to
1615  * use the default one, because the default one always calls
1616  * gtk_drag_finish and we prefer to do it in the "drag-data-received"
1617  * signal handler, because there we have all the information available
1618  * to know if the dnd was a success or not.
1619  */
1620 static gboolean
1621 drag_drop_cb (GtkWidget      *widget,
1622               GdkDragContext *context,
1623               gint            x,
1624               gint            y,
1625               guint           time,
1626               gpointer        user_data) 
1627 {
1628         gpointer target;
1629
1630         if (!context->targets)
1631                 return FALSE;
1632
1633         /* Check if we're dragging a folder row */
1634         target = gtk_drag_dest_find_target (widget, context, NULL);
1635
1636         /* Request the data from the source. */
1637         gtk_drag_get_data(widget, context, target, time);
1638
1639     return TRUE;
1640 }
1641
1642 /*
1643  * This function expands a node of a tree view if it's not expanded
1644  * yet. Not sure why it needs the threads stuff, but gtk+`example code
1645  * does that, so that's why they're here.
1646  */
1647 static gint
1648 expand_row_timeout (gpointer data)
1649 {
1650         GtkTreeView *tree_view = data;
1651         GtkTreePath *dest_path = NULL;
1652         GtkTreeViewDropPosition pos;
1653         gboolean result = FALSE;
1654         
1655         GDK_THREADS_ENTER ();
1656         
1657         gtk_tree_view_get_drag_dest_row (tree_view,
1658                                          &dest_path,
1659                                          &pos);
1660         
1661         if (dest_path &&
1662             (pos == GTK_TREE_VIEW_DROP_INTO_OR_AFTER ||
1663              pos == GTK_TREE_VIEW_DROP_INTO_OR_BEFORE)) {
1664                 gtk_tree_view_expand_row (tree_view, dest_path, FALSE);
1665                 gtk_tree_path_free (dest_path);
1666         }
1667         else {
1668                 if (dest_path)
1669                         gtk_tree_path_free (dest_path);
1670                 
1671                 result = TRUE;
1672         }
1673         
1674         GDK_THREADS_LEAVE ();
1675
1676         return result;
1677 }
1678
1679 /*
1680  * This function is called whenever the pointer is moved over a widget
1681  * while dragging some data. It installs a timeout that will expand a
1682  * node of the treeview if not expanded yet. This function also calls
1683  * gdk_drag_status in order to set the suggested action that will be
1684  * used by the "drag-data-received" signal handler to know if we
1685  * should do a move or just a copy of the data.
1686  */
1687 static gboolean
1688 on_drag_motion (GtkWidget      *widget,
1689                 GdkDragContext *context,
1690                 gint            x,
1691                 gint            y,
1692                 guint           time,
1693                 gpointer        user_data)  
1694 {
1695         GtkTreeViewDropPosition pos;
1696         GtkTreePath *dest_row;
1697         ModestFolderViewPrivate *priv;
1698         GdkDragAction suggested_action;
1699         gboolean valid_location = FALSE;
1700
1701         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (widget);
1702
1703         if (priv->timer_expander != 0) {
1704                 g_source_remove (priv->timer_expander);
1705                 priv->timer_expander = 0;
1706         }
1707
1708         gtk_tree_view_get_dest_row_at_pos (GTK_TREE_VIEW (widget),
1709                                            x, y,
1710                                            &dest_row,
1711                                            &pos);
1712
1713         /* Do not allow drops between folders */
1714         if (!dest_row ||
1715             pos == GTK_TREE_VIEW_DROP_BEFORE ||
1716             pos == GTK_TREE_VIEW_DROP_AFTER) {
1717                 gtk_tree_view_set_drag_dest_row(GTK_TREE_VIEW (widget), NULL, 0);
1718                 gdk_drag_status(context, 0, time);
1719                 valid_location = FALSE;
1720                 goto out;
1721         } else {
1722                 valid_location = TRUE;
1723         }
1724
1725         /* Expand the selected row after 1/2 second */
1726         if (!gtk_tree_view_row_expanded (GTK_TREE_VIEW (widget), dest_row)) {
1727                 gtk_tree_view_set_drag_dest_row (GTK_TREE_VIEW (widget), dest_row, pos);
1728                 priv->timer_expander = g_timeout_add (500, expand_row_timeout, widget);
1729         }
1730
1731         /* Select the desired action. By default we pick MOVE */
1732         suggested_action = GDK_ACTION_MOVE;
1733
1734         if (context->actions == GDK_ACTION_COPY)
1735             gdk_drag_status(context, GDK_ACTION_COPY, time);
1736         else if (context->actions == GDK_ACTION_MOVE)
1737             gdk_drag_status(context, GDK_ACTION_MOVE, time);
1738         else if (context->actions & suggested_action)
1739             gdk_drag_status(context, suggested_action, time);
1740         else
1741             gdk_drag_status(context, GDK_ACTION_DEFAULT, time);
1742
1743  out:
1744         if (dest_row)
1745                 gtk_tree_path_free (dest_row);
1746         g_signal_stop_emission_by_name (widget, "drag-motion");
1747         return valid_location;
1748 }
1749
1750
1751 /* Folder view drag types */
1752 const GtkTargetEntry folder_view_drag_types[] =
1753 {
1754         { "GTK_TREE_MODEL_ROW", GTK_TARGET_SAME_WIDGET, MODEST_FOLDER_ROW },
1755         { "GTK_TREE_MODEL_ROW", GTK_TARGET_SAME_APP,    MODEST_HEADER_ROW }
1756 };
1757
1758 /*
1759  * This function sets the treeview as a source and a target for dnd
1760  * events. It also connects all the requirede signals.
1761  */
1762 static void
1763 setup_drag_and_drop (GtkTreeView *self)
1764 {
1765         /* Set up the folder view as a dnd destination. Set only the
1766            highlight flag, otherwise gtk will have a different
1767            behaviour */
1768         gtk_drag_dest_set (GTK_WIDGET (self),
1769                            GTK_DEST_DEFAULT_HIGHLIGHT,
1770                            folder_view_drag_types,
1771                            G_N_ELEMENTS (folder_view_drag_types),
1772                            GDK_ACTION_MOVE | GDK_ACTION_COPY);
1773
1774         g_signal_connect (G_OBJECT (self),
1775                           "drag_data_received",
1776                           G_CALLBACK (on_drag_data_received),
1777                           NULL);
1778
1779
1780         /* Set up the treeview as a dnd source */
1781         gtk_drag_source_set (GTK_WIDGET (self),
1782                              GDK_BUTTON1_MASK,
1783                              folder_view_drag_types,
1784                              G_N_ELEMENTS (folder_view_drag_types),
1785                              GDK_ACTION_MOVE | GDK_ACTION_COPY);
1786
1787         g_signal_connect (G_OBJECT (self),
1788                           "drag_motion",
1789                           G_CALLBACK (on_drag_motion),
1790                           NULL);
1791         
1792         g_signal_connect (G_OBJECT (self),
1793                           "drag_data_get",
1794                           G_CALLBACK (on_drag_data_get),
1795                           NULL);
1796
1797         g_signal_connect (G_OBJECT (self),
1798                           "drag_drop",
1799                           G_CALLBACK (drag_drop_cb),
1800                           NULL);
1801 }
1802
1803 /*
1804  * This function manages the navigation through the folders using the
1805  * keyboard or the hardware keys in the device
1806  */
1807 static gboolean
1808 on_key_pressed (GtkWidget *self,
1809                 GdkEventKey *event,
1810                 gpointer user_data)
1811 {
1812         GtkTreeSelection *selection;
1813         GtkTreeIter iter;
1814         GtkTreeModel *model;
1815         gboolean retval = FALSE;
1816
1817         /* Up and Down are automatically managed by the treeview */
1818         if (event->keyval == GDK_Return) {
1819                 /* Expand/Collapse the selected row */
1820                 selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (self));
1821                 if (gtk_tree_selection_get_selected (selection, &model, &iter)) {
1822                         GtkTreePath *path;
1823
1824                         path = gtk_tree_model_get_path (model, &iter);
1825
1826                         if (gtk_tree_view_row_expanded (GTK_TREE_VIEW (self), path))
1827                                 gtk_tree_view_collapse_row (GTK_TREE_VIEW (self), path);
1828                         else
1829                                 gtk_tree_view_expand_row (GTK_TREE_VIEW (self), path, FALSE);
1830                         gtk_tree_path_free (path);
1831                 }
1832                 /* No further processing */
1833                 retval = TRUE;
1834         }
1835
1836         return retval;
1837 }
1838
1839 /*
1840  * We listen to the changes in the local folder account name key,
1841  * because we want to show the right name in the view. The local
1842  * folder account name corresponds to the device name in the Maemo
1843  * version. We do this because we do not want to query gconf on each
1844  * tree view refresh. It's better to cache it and change whenever
1845  * necessary.
1846  */
1847 static void 
1848 on_configuration_key_changed (ModestConf* conf, 
1849                               const gchar *key, 
1850                               ModestConfEvent event, 
1851                               ModestFolderView *self)
1852 {
1853         ModestFolderViewPrivate *priv;
1854
1855         if (!key)
1856                 return;
1857
1858         g_return_if_fail (MODEST_IS_FOLDER_VIEW (self));
1859         priv = MODEST_FOLDER_VIEW_GET_PRIVATE(self);
1860
1861         if (!strcmp (key, MODEST_CONF_DEVICE_NAME)) {
1862                 g_free (priv->local_account_name);
1863
1864                 if (event == MODEST_CONF_EVENT_KEY_UNSET)
1865                         priv->local_account_name = g_strdup (MODEST_LOCAL_FOLDERS_DEFAULT_DISPLAY_NAME);
1866                 else
1867                         priv->local_account_name = modest_conf_get_string (modest_runtime_get_conf(),
1868                                                                            MODEST_CONF_DEVICE_NAME, NULL);
1869
1870                 /* Force a redraw */
1871 #if GTK_CHECK_VERSION(2, 8, 0) /* gtk_tree_view_column_queue_resize is only available in GTK+ 2.8 */
1872                 GtkTreeViewColumn * tree_column = gtk_tree_view_get_column (GTK_TREE_VIEW (self), 
1873                                                                             TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN);
1874                 gtk_tree_view_column_queue_resize (tree_column);
1875 #endif
1876         }
1877 }
1878
1879 void 
1880 modest_folder_view_set_style (ModestFolderView *self,
1881                               ModestFolderViewStyle style)
1882 {
1883         ModestFolderViewPrivate *priv;
1884
1885         g_return_if_fail (self);
1886         
1887         priv = MODEST_FOLDER_VIEW_GET_PRIVATE(self);
1888
1889         priv->style = style;
1890 }
1891
1892 void
1893 modest_folder_view_set_account_id_of_visible_server_account (ModestFolderView *self,
1894                                                              const gchar *account_id)
1895 {
1896         ModestFolderViewPrivate *priv;
1897         GtkTreeModel *model;
1898
1899         g_return_if_fail (self);
1900         
1901         priv = MODEST_FOLDER_VIEW_GET_PRIVATE(self);
1902
1903         /* This will be used by the filter_row callback,
1904          * to decided which rows to show: */
1905         if (priv->visible_account_id) {
1906                 g_free (priv->visible_account_id);
1907                 priv->visible_account_id = NULL;
1908         }
1909         if (account_id)
1910                 priv->visible_account_id = g_strdup (account_id);
1911
1912         /* Refilter */
1913         model = gtk_tree_view_get_model (GTK_TREE_VIEW (self));
1914         if (GTK_IS_TREE_MODEL_FILTER (model))
1915                 gtk_tree_model_filter_refilter (GTK_TREE_MODEL_FILTER (model));
1916
1917         /* Save settings to gconf */
1918         modest_widget_memory_save (modest_runtime_get_conf (), G_OBJECT(self),
1919                                    MODEST_CONF_FOLDER_VIEW_KEY);
1920 }
1921
1922 const gchar *
1923 modest_folder_view_get_account_id_of_visible_server_account (ModestFolderView *self)
1924 {
1925         ModestFolderViewPrivate *priv;
1926
1927         g_return_val_if_fail (self, NULL);
1928         
1929         priv = MODEST_FOLDER_VIEW_GET_PRIVATE(self);
1930
1931         return (const gchar *) priv->visible_account_id;
1932 }
1933
1934 static gboolean
1935 find_inbox_iter (GtkTreeModel *model, GtkTreeIter *iter, GtkTreeIter *inbox_iter)
1936 {
1937         do {
1938                 GtkTreeIter child;
1939                 TnyFolderType type = TNY_FOLDER_TYPE_UNKNOWN;
1940                 gchar *name = NULL;
1941
1942                 gtk_tree_model_get (model, iter, 
1943                                     TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN, &name,
1944                                     TNY_GTK_FOLDER_STORE_TREE_MODEL_TYPE_COLUMN, 
1945                                     &type, -1);
1946
1947                 /*
1948                 printf ("DEBUG: %s: name=%s, type=%d, TNY_FOLDER_TYPE_INBOX=%d\n", 
1949                         __FUNCTION__, name, type, TNY_FOLDER_TYPE_INBOX);
1950                 */
1951                         
1952                 gboolean result = FALSE;
1953                 if (type == TNY_FOLDER_TYPE_INBOX) {
1954                         result = TRUE;
1955                 } else if (type == TNY_FOLDER_TYPE_NORMAL) {
1956                         /* tinymail's camel implementation only provides TNY_FOLDER_TYPE_NORMAL
1957                          * when getting folders from the cache, before connectin, so we do 
1958                          * an extra check. We could fix this in tinymail, but it's easier 
1959                          * to do here.
1960                          */
1961                          if (strcmp (name, "Inbox") == 0)
1962                                 result = TRUE;
1963                 }
1964                 
1965                 g_free (name);
1966                 
1967                 if (result) {
1968                         *inbox_iter = *iter;
1969                         return TRUE;
1970                 }
1971
1972                 if (gtk_tree_model_iter_children (model, &child, iter)) {
1973                         if (find_inbox_iter (model, &child, inbox_iter))
1974                                 return TRUE;
1975                 }
1976
1977         } while (gtk_tree_model_iter_next (model, iter));
1978
1979         return FALSE;
1980 }
1981
1982 void 
1983 modest_folder_view_select_first_inbox_or_local (ModestFolderView *self)
1984 {
1985         GtkTreeModel *model;
1986         GtkTreeIter iter, inbox_iter;
1987         GtkTreeSelection *sel;
1988
1989 /*      /\* Do not set it if the folder view was not painted *\/ */
1990 /*      if (!GTK_WIDGET_MAPPED (self)) */
1991 /*              return; */
1992
1993         model = gtk_tree_view_get_model (GTK_TREE_VIEW (self));
1994         if (!model)
1995                 return;
1996
1997         expand_root_items (self);
1998         sel = gtk_tree_view_get_selection (GTK_TREE_VIEW (self));
1999
2000         gtk_tree_model_get_iter_first (model, &iter);
2001         if (find_inbox_iter (model, &iter, &inbox_iter)) {
2002                 gtk_tree_selection_select_iter (sel, &inbox_iter);
2003         }
2004         else {
2005                 gtk_tree_model_get_iter_first (model, &iter);
2006                 gtk_tree_selection_select_iter (sel, &iter);
2007         }
2008 }
2009
2010 void 
2011 modest_folder_view_copy_selection (ModestFolderView *folder_view)
2012 {
2013         /* Copy selection */
2014         _clipboard_set_selected_data (folder_view, FALSE);
2015 }
2016
2017 void 
2018 modest_folder_view_cut_selection (ModestFolderView *folder_view)
2019 {
2020         ModestFolderViewPrivate *priv = NULL;
2021         GtkTreeModel *model = NULL;
2022         const gchar **hidding = NULL;
2023         guint i, n_selected;
2024
2025         g_return_if_fail (MODEST_IS_FOLDER_VIEW (folder_view));
2026         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (folder_view);
2027
2028         /* Copy selection */
2029         if (!_clipboard_set_selected_data (folder_view, TRUE))
2030                 return;
2031
2032         /* Get hidding ids */
2033         hidding = modest_email_clipboard_get_hidding_ids (priv->clipboard, &n_selected); 
2034         
2035         /* Clear hidding array created by previous cut operation */
2036         _clear_hidding_filter (MODEST_FOLDER_VIEW (folder_view));
2037
2038         /* Copy hidding array */
2039         priv->n_selected = n_selected;
2040         priv->hidding_ids = g_malloc0(sizeof(gchar *) * n_selected);
2041         for (i=0; i < n_selected; i++) 
2042                 priv->hidding_ids[i] = g_strdup(hidding[i]);            
2043
2044         /* Hide cut folders */
2045         model = gtk_tree_view_get_model (GTK_TREE_VIEW (folder_view));
2046         gtk_tree_model_filter_refilter (GTK_TREE_MODEL_FILTER (model));
2047 }
2048
2049 /* Returns FALSE if it did not selected anything */
2050 static gboolean
2051 _clipboard_set_selected_data (ModestFolderView *folder_view,
2052                               gboolean delete)
2053 {
2054         ModestFolderViewPrivate *priv = NULL;
2055         TnyFolderStore *folder = NULL;
2056         gboolean retval = FALSE;
2057
2058         g_return_val_if_fail (MODEST_IS_FOLDER_VIEW (folder_view), FALSE);
2059         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (folder_view);
2060                 
2061         /* Set selected data on clipboard   */
2062         g_return_val_if_fail (MODEST_IS_EMAIL_CLIPBOARD (priv->clipboard), FALSE);
2063         folder = modest_folder_view_get_selected (folder_view);
2064
2065         /* Do not allow to select an account */
2066         if (TNY_IS_FOLDER (folder)) {
2067                 modest_email_clipboard_set_data (priv->clipboard, TNY_FOLDER(folder), NULL, delete);
2068                 retval = TRUE;
2069         }
2070
2071         /* Free */
2072         g_object_unref (folder);
2073
2074         return retval;
2075 }
2076
2077 static void
2078 _clear_hidding_filter (ModestFolderView *folder_view) 
2079 {
2080         ModestFolderViewPrivate *priv;
2081         guint i;
2082         
2083         g_return_if_fail (MODEST_IS_FOLDER_VIEW (folder_view)); 
2084         priv = MODEST_FOLDER_VIEW_GET_PRIVATE(folder_view);
2085
2086         if (priv->hidding_ids != NULL) {
2087                 for (i=0; i < priv->n_selected; i++) 
2088                         g_free (priv->hidding_ids[i]);
2089                 g_free(priv->hidding_ids);
2090         }       
2091 }