2007-04-15 Sergio Villar Senin <svillar@igalia.com>
[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
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-account-store.h>
39 #include <tny-account.h>
40 #include <tny-folder.h>
41 #include <tny-camel-folder.h>
42 #include <tny-simple-list.h>
43 #include <modest-tny-folder.h>
44 #include <modest-marshal.h>
45 #include <modest-icon-names.h>
46 #include <modest-tny-account-store.h>
47 #include <modest-text-utils.h>
48 #include <modest-runtime.h>
49 #include "modest-folder-view.h"
50 #include <modest-dnd.h>
51 #include <modest-platform.h>
52
53 /* 'private'/'protected' functions */
54 static void modest_folder_view_class_init  (ModestFolderViewClass *klass);
55 static void modest_folder_view_init        (ModestFolderView *obj);
56 static void modest_folder_view_finalize    (GObject *obj);
57
58 static void         tny_account_store_view_init (gpointer g, 
59                                                  gpointer iface_data);
60
61 static void         modest_folder_view_set_account_store (TnyAccountStoreView *self, 
62                                                           TnyAccountStore     *account_store);
63
64 static gboolean     update_model           (ModestFolderView *self,
65                                             ModestTnyAccountStore *account_store);
66
67 static void         on_selection_changed   (GtkTreeSelection *sel, gpointer data);
68
69 static void         on_account_update      (TnyAccountStore *account_store, 
70                                             const gchar *account,
71                                             gpointer user_data);
72
73 static void         on_accounts_reloaded   (TnyAccountStore *store, 
74                                             gpointer user_data);
75
76 static gint         cmp_rows               (GtkTreeModel *tree_model, 
77                                             GtkTreeIter *iter1, 
78                                             GtkTreeIter *iter2,
79                                             gpointer user_data);
80
81 /* DnD functions */
82 static void         on_drag_data_get       (GtkWidget *widget, 
83                                             GdkDragContext *context, 
84                                             GtkSelectionData *selection_data, 
85                                             guint info, 
86                                             guint time, 
87                                             gpointer data);
88
89 static void         on_drag_data_received  (GtkWidget *widget, 
90                                             GdkDragContext *context, 
91                                             gint x, 
92                                             gint y, 
93                                             GtkSelectionData *selection_data, 
94                                             guint info, 
95                                             guint time, 
96                                             gpointer data);
97
98 static gboolean     on_drag_motion         (GtkWidget      *widget,
99                                             GdkDragContext *context,
100                                             gint            x,
101                                             gint            y,
102                                             guint           time,
103                                             gpointer        user_data);
104
105 static gint         expand_row_timeout     (gpointer data);
106
107 static void         setup_drag_and_drop    (GtkTreeView *self);
108
109 enum {
110         FOLDER_SELECTION_CHANGED_SIGNAL,
111         LAST_SIGNAL
112 };
113
114 typedef struct _ModestFolderViewPrivate ModestFolderViewPrivate;
115 struct _ModestFolderViewPrivate {
116         TnyAccountStore     *account_store;
117         TnyFolder           *cur_folder;
118         GtkTreeRowReference *cur_row;
119
120         gulong               account_update_signal;
121         gulong               changed_signal;
122         gulong               accounts_reloaded_signal;
123         
124         GtkTreeSelection    *cur_selection;
125         TnyFolderStoreQuery *query;
126         guint                timer_expander;
127 };
128 #define MODEST_FOLDER_VIEW_GET_PRIVATE(o)                       \
129         (G_TYPE_INSTANCE_GET_PRIVATE((o),                       \
130                                      MODEST_TYPE_FOLDER_VIEW,   \
131                                      ModestFolderViewPrivate))
132 /* globals */
133 static GObjectClass *parent_class = NULL;
134
135 static guint signals[LAST_SIGNAL] = {0}; 
136
137 GType
138 modest_folder_view_get_type (void)
139 {
140         static GType my_type = 0;
141         if (!my_type) {
142                 static const GTypeInfo my_info = {
143                         sizeof(ModestFolderViewClass),
144                         NULL,           /* base init */
145                         NULL,           /* base finalize */
146                         (GClassInitFunc) modest_folder_view_class_init,
147                         NULL,           /* class finalize */
148                         NULL,           /* class data */
149                         sizeof(ModestFolderView),
150                         1,              /* n_preallocs */
151                         (GInstanceInitFunc) modest_folder_view_init,
152                         NULL
153                 };
154
155                 static const GInterfaceInfo tny_account_store_view_info = {
156                         (GInterfaceInitFunc) tny_account_store_view_init, /* interface_init */
157                         NULL,         /* interface_finalize */
158                         NULL          /* interface_data */
159                 };
160
161                                 
162                 my_type = g_type_register_static (GTK_TYPE_TREE_VIEW,
163                                                   "ModestFolderView",
164                                                   &my_info, 0);
165
166                 g_type_add_interface_static (my_type, 
167                                              TNY_TYPE_ACCOUNT_STORE_VIEW, 
168                                              &tny_account_store_view_info);
169         }
170         return my_type;
171 }
172
173 static void
174 modest_folder_view_class_init (ModestFolderViewClass *klass)
175 {
176         GObjectClass *gobject_class;
177         gobject_class = (GObjectClass*) klass;
178
179         parent_class            = g_type_class_peek_parent (klass);
180         gobject_class->finalize = modest_folder_view_finalize;
181
182         g_type_class_add_private (gobject_class,
183                                   sizeof(ModestFolderViewPrivate));
184         
185         signals[FOLDER_SELECTION_CHANGED_SIGNAL] = 
186                 g_signal_new ("folder_selection_changed",
187                               G_TYPE_FROM_CLASS (gobject_class),
188                               G_SIGNAL_RUN_FIRST,
189                               G_STRUCT_OFFSET (ModestFolderViewClass,
190                                                folder_selection_changed),
191                               NULL, NULL,
192                               modest_marshal_VOID__POINTER_BOOLEAN,
193                               G_TYPE_NONE, 2, G_TYPE_POINTER, G_TYPE_BOOLEAN);
194 }
195
196
197
198 static void
199 text_cell_data  (GtkTreeViewColumn *column,  GtkCellRenderer *renderer,
200                  GtkTreeModel *tree_model,  GtkTreeIter *iter,  gpointer data)
201 {
202         GObject *rendobj;
203         gchar *fname = NULL;
204         gint unread;
205         TnyFolderType type;
206         TnyFolder *folder = NULL;
207         
208         g_return_if_fail (column);
209         g_return_if_fail (tree_model);
210
211         gtk_tree_model_get (tree_model, iter,
212                             TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN, &fname,
213                             TNY_GTK_FOLDER_STORE_TREE_MODEL_UNREAD_COLUMN, &unread,
214                             TNY_GTK_FOLDER_STORE_TREE_MODEL_TYPE_COLUMN, &type,
215                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, &folder,
216                             -1);
217         rendobj = G_OBJECT(renderer);
218  
219         if (!fname)
220                 return;
221         
222         if (folder && type != TNY_FOLDER_TYPE_ROOT) { /* FIXME: tnymail bug? crashes with root folders */
223                 if (modest_tny_folder_is_local_folder (folder)) {
224                         TnyFolderType type;
225                         type = modest_tny_folder_get_local_folder_type (folder);
226                         if (type != TNY_FOLDER_TYPE_UNKNOWN) {
227                                 g_free (fname);
228                                 fname = g_strdup(modest_local_folder_info_get_type_display_name (type));
229                         }
230                 }
231         } else if (folder && type == TNY_FOLDER_TYPE_ROOT) {
232                 /* FIXME: todo */
233         }
234                         
235         if (unread > 0) {
236                 gchar *folder_title = g_strdup_printf ("%s (%d)", fname, unread);
237                 g_object_set (rendobj,"text", folder_title,  "weight", 800, NULL);
238                 g_free (folder_title);
239         } else 
240                 g_object_set (rendobj,"text", fname, "weight", 400, NULL);
241                 
242         g_free (fname);
243         if (folder) g_object_unref (G_OBJECT (folder));
244 }
245
246
247
248 static void
249 icon_cell_data  (GtkTreeViewColumn *column,  GtkCellRenderer *renderer,
250                  GtkTreeModel *tree_model,  GtkTreeIter *iter, gpointer data)
251 {
252         GObject *rendobj;
253         GdkPixbuf *pixbuf;
254         TnyFolderType type;
255         gchar *fname = NULL;
256         gint unread;
257         
258         rendobj = G_OBJECT(renderer);
259         gtk_tree_model_get (tree_model, iter,
260                             TNY_GTK_FOLDER_STORE_TREE_MODEL_TYPE_COLUMN, &type,
261                             TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN, &fname,
262                             TNY_GTK_FOLDER_STORE_TREE_MODEL_UNREAD_COLUMN, &unread, 
263                             -1);
264         rendobj = G_OBJECT(renderer);
265         
266         if (type == TNY_FOLDER_TYPE_NORMAL || type == TNY_FOLDER_TYPE_UNKNOWN) {
267                 type = modest_tny_folder_guess_folder_type_from_name (fname);
268         }
269         g_free (fname);
270
271         switch (type) {
272         case TNY_FOLDER_TYPE_ROOT:
273                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_ACCOUNT);
274                 break;
275         case TNY_FOLDER_TYPE_INBOX:
276                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_INBOX);
277                 break;
278         case TNY_FOLDER_TYPE_OUTBOX:
279                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_OUTBOX);
280                 break;
281         case TNY_FOLDER_TYPE_JUNK:
282                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_JUNK);
283                 break;
284         case TNY_FOLDER_TYPE_SENT:
285                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_SENT);
286                 break;
287         case TNY_FOLDER_TYPE_TRASH:
288                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_TRASH);
289                 break;
290         case TNY_FOLDER_TYPE_DRAFTS:
291                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_DRAFTS);
292                 break;
293         case TNY_FOLDER_TYPE_NORMAL:
294         default:
295                 pixbuf = modest_platform_get_icon (MODEST_FOLDER_ICON_NORMAL);
296                 break;
297         }
298         g_object_set (rendobj, "pixbuf", pixbuf, NULL);
299 }
300
301 static void
302 modest_folder_view_init (ModestFolderView *obj)
303 {
304         ModestFolderViewPrivate *priv;
305         GtkTreeViewColumn *column;
306         GtkCellRenderer *renderer;
307         GtkTreeSelection *sel;
308         
309         priv =  MODEST_FOLDER_VIEW_GET_PRIVATE(obj);
310         
311         priv->timer_expander = 0;
312         priv->account_store  = NULL;
313         priv->cur_folder     = NULL;
314         priv->cur_row        = NULL;
315         priv->query          = NULL;
316
317         column = gtk_tree_view_column_new ();   
318         
319         renderer = gtk_cell_renderer_pixbuf_new();
320         gtk_tree_view_column_pack_start (column, renderer, FALSE);
321         gtk_tree_view_column_set_cell_data_func(column, renderer,
322                                                 icon_cell_data, NULL, NULL);
323         
324         renderer = gtk_cell_renderer_text_new();
325         gtk_tree_view_column_pack_start (column, renderer, FALSE);
326         gtk_tree_view_column_set_cell_data_func(column, renderer,
327                                                 text_cell_data, NULL, NULL);
328         
329         sel = gtk_tree_view_get_selection (GTK_TREE_VIEW(obj));
330         gtk_tree_selection_set_mode (sel, GTK_SELECTION_SINGLE);
331
332         gtk_tree_view_column_set_spacing (column, 2);
333         gtk_tree_view_column_set_resizable (column, TRUE);
334         gtk_tree_view_column_set_fixed_width (column, TRUE);            
335         gtk_tree_view_set_headers_clickable (GTK_TREE_VIEW(obj), FALSE);
336         gtk_tree_view_set_enable_search     (GTK_TREE_VIEW(obj), FALSE);
337
338         gtk_tree_view_append_column (GTK_TREE_VIEW(obj),column);
339
340         setup_drag_and_drop (GTK_TREE_VIEW(obj));
341 }
342
343 static void
344 tny_account_store_view_init (gpointer g, gpointer iface_data)
345 {
346         TnyAccountStoreViewIface *klass = (TnyAccountStoreViewIface *)g;
347
348         klass->set_account_store_func = modest_folder_view_set_account_store;
349
350         return;
351 }
352
353 static void
354 modest_folder_view_finalize (GObject *obj)
355 {
356         ModestFolderViewPrivate *priv;
357         GtkTreeSelection    *sel;
358         
359         g_return_if_fail (obj);
360         
361         priv =  MODEST_FOLDER_VIEW_GET_PRIVATE(obj);
362
363         if (priv->timer_expander != 0) {
364                 g_source_remove (priv->timer_expander);
365                 priv->timer_expander = 0;
366         }
367
368         if (priv->account_store) {
369                 g_signal_handler_disconnect (G_OBJECT(priv->account_store),
370                                              priv->account_update_signal);
371                 g_signal_handler_disconnect (G_OBJECT(priv->account_store),
372                                              priv->accounts_reloaded_signal);
373                 g_object_unref (G_OBJECT(priv->account_store));
374                 priv->account_store = NULL;
375         }
376
377         if (priv->query) {
378                 g_object_unref (G_OBJECT (priv->query));
379                 priv->query = NULL;
380         }
381
382         sel = gtk_tree_view_get_selection (GTK_TREE_VIEW(obj));
383         if (sel)
384                 g_signal_handler_disconnect (G_OBJECT(sel), priv->changed_signal);
385         
386         G_OBJECT_CLASS(parent_class)->finalize (obj);
387 }
388
389
390 static void
391 modest_folder_view_set_account_store (TnyAccountStoreView *self, TnyAccountStore *account_store)
392 {
393         ModestFolderViewPrivate *priv;
394         TnyDevice *device;
395
396         g_return_if_fail (MODEST_IS_FOLDER_VIEW (self));
397         g_return_if_fail (TNY_IS_ACCOUNT_STORE (account_store));
398
399         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (self);
400         device = tny_account_store_get_device (account_store);
401
402         if (G_UNLIKELY (priv->account_store)) {
403
404                 if (g_signal_handler_is_connected (G_OBJECT (priv->account_store), 
405                                                    priv->account_update_signal))
406                         g_signal_handler_disconnect (G_OBJECT (priv->account_store), 
407                                                      priv->account_update_signal);
408                 if (g_signal_handler_is_connected (G_OBJECT (priv->account_store), 
409                                                    priv->accounts_reloaded_signal))
410                         g_signal_handler_disconnect (G_OBJECT (priv->account_store), 
411                                                      priv->accounts_reloaded_signal);
412
413                 g_object_unref (G_OBJECT (priv->account_store));
414         }
415
416         priv->account_store = g_object_ref (G_OBJECT (account_store));
417
418         priv->account_update_signal = 
419                 g_signal_connect (G_OBJECT(account_store), "account_update",
420                                   G_CALLBACK (on_account_update), self);
421
422         priv->accounts_reloaded_signal = 
423                 g_signal_connect (G_OBJECT(account_store), "accounts_reloaded",
424                                   G_CALLBACK (on_accounts_reloaded), self);
425         
426         if (!update_model (MODEST_FOLDER_VIEW (self),
427                            MODEST_TNY_ACCOUNT_STORE (priv->account_store)))
428                 g_printerr ("modest: failed to update model\n");
429
430         g_object_unref (G_OBJECT (device));
431 }
432
433 static void
434 on_account_update (TnyAccountStore *account_store, const gchar *account,
435                    gpointer user_data)
436 {
437         if (!update_model (MODEST_FOLDER_VIEW(user_data), 
438                            MODEST_TNY_ACCOUNT_STORE(account_store)))
439                 g_printerr ("modest: failed to update model for changes in '%s'",
440                             account);
441 }
442
443 static void 
444 on_accounts_reloaded   (TnyAccountStore *account_store, 
445                         gpointer user_data)
446 {
447         update_model (MODEST_FOLDER_VIEW (user_data), 
448                       MODEST_TNY_ACCOUNT_STORE(account_store));
449 }
450
451 void
452 modest_folder_view_set_title (ModestFolderView *self, const gchar *title)
453 {
454         GtkTreeViewColumn *col;
455         
456         g_return_if_fail (self);
457
458         col = gtk_tree_view_get_column (GTK_TREE_VIEW(self), 0);
459         if (!col) {
460                 g_printerr ("modest: failed get column for title\n");
461                 return;
462         }
463
464         gtk_tree_view_column_set_title (col, title);
465         gtk_tree_view_set_headers_visible (GTK_TREE_VIEW(self),
466                                            title != NULL);
467 }
468
469 GtkWidget*
470 modest_folder_view_new (TnyFolderStoreQuery *query)
471 {
472         GObject *self;
473         ModestFolderViewPrivate *priv;
474         GtkTreeSelection *sel;
475         
476         self = G_OBJECT (g_object_new (MODEST_TYPE_FOLDER_VIEW, NULL));
477         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (self);
478
479         priv->query = g_object_ref (query);
480         
481         sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(self));
482         priv->changed_signal = g_signal_connect (sel, "changed",
483                                                  G_CALLBACK (on_selection_changed), self);
484         return GTK_WIDGET(self);
485 }
486
487 /* this feels dirty; any other way to expand all the root items? */
488 static void
489 expand_root_items (ModestFolderView *self)
490 {
491         GtkTreePath *path;
492         path = gtk_tree_path_new_first ();
493
494         /* all folders should have child items, so.. */
495         while (gtk_tree_view_expand_row (GTK_TREE_VIEW(self), path, FALSE))
496                 gtk_tree_path_next (path);
497         
498         gtk_tree_path_free (path);
499 }
500
501 static gboolean
502 update_model (ModestFolderView *self, ModestTnyAccountStore *account_store)
503 {
504         ModestFolderViewPrivate *priv;
505
506         TnyList          *account_list;
507         GtkTreeModel     *model, *sortable;
508
509         g_return_val_if_fail (account_store, FALSE);
510
511         priv =  MODEST_FOLDER_VIEW_GET_PRIVATE(self);
512         
513         /* Notify that there is no folder selected*/
514         g_signal_emit (G_OBJECT(self), 
515                        signals[FOLDER_SELECTION_CHANGED_SIGNAL], 0,
516                        NULL, TRUE);
517         
518         /* FIXME: the local accounts are not shown when the query
519            selects only the subscribed folders. */
520 /*      model        = tny_gtk_folder_store_tree_model_new (TRUE, priv->query); */
521         model        = tny_gtk_folder_store_tree_model_new (TRUE, NULL);
522         account_list = TNY_LIST(model);
523
524         tny_account_store_get_accounts (TNY_ACCOUNT_STORE(account_store),
525                                         account_list,
526                                         TNY_ACCOUNT_STORE_STORE_ACCOUNTS);      
527         if (account_list) {
528                 sortable = gtk_tree_model_sort_new_with_model (model);
529                 gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE(sortable),
530                                                       TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN, 
531                                                       GTK_SORT_ASCENDING);
532                 gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (sortable),
533                                                  TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN,
534                                                  cmp_rows, NULL, NULL);
535
536                 /* Set new model */
537                 gtk_tree_view_set_model (GTK_TREE_VIEW(self), sortable);
538                 expand_root_items (self); /* expand all account folders */
539                 g_object_unref (account_list);
540         }
541         
542         return TRUE;
543 }
544
545
546 static void
547 on_selection_changed (GtkTreeSelection *sel, gpointer user_data)
548 {
549         GtkTreeModel            *model_sort, *model;
550         TnyFolder               *folder = NULL;
551         GtkTreeIter             iter, iter_sort;
552         GtkTreePath            *path;
553         ModestFolderView        *tree_view;
554         ModestFolderViewPrivate *priv;
555         gint                    type;
556
557         g_return_if_fail (sel);
558         g_return_if_fail (user_data);
559         
560         priv = MODEST_FOLDER_VIEW_GET_PRIVATE(user_data);
561         priv->cur_selection = sel;
562         
563         /* folder was _un_selected if true */
564         if (!gtk_tree_selection_get_selected (sel, &model_sort, &iter_sort)) {
565                 if (priv->cur_folder)
566                         g_object_unref (priv->cur_folder);
567                 if (priv->cur_row)
568                         gtk_tree_row_reference_free (priv->cur_row);
569                 priv->cur_folder = NULL;
570                 priv->cur_row = NULL;
571                 return; 
572         }
573
574         model = gtk_tree_model_sort_get_model (GTK_TREE_MODEL_SORT (model_sort));
575         gtk_tree_model_sort_convert_iter_to_child_iter (GTK_TREE_MODEL_SORT (model_sort),
576                                                         &iter,
577                                                         &iter_sort);
578
579         tree_view = MODEST_FOLDER_VIEW (user_data);
580
581         gtk_tree_model_get (model, &iter,
582                             TNY_GTK_FOLDER_STORE_TREE_MODEL_TYPE_COLUMN, &type,
583                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, &folder,
584                             -1);
585
586         /* If the folder is the same or is a root folder do not notify */
587         if ((type == TNY_FOLDER_TYPE_ROOT) || (priv->cur_folder == folder)) {
588                 g_object_unref (folder);
589                 return;
590         }
591         
592         /* Current folder was unselected */
593         if (priv->cur_folder) {
594                 g_signal_emit (G_OBJECT(tree_view), signals[FOLDER_SELECTION_CHANGED_SIGNAL], 0,
595                                priv->cur_folder, FALSE);
596                 g_object_unref (priv->cur_folder);
597         }
598
599         if (priv->cur_row)
600                 gtk_tree_row_reference_free (priv->cur_row);
601
602         /* New current references */
603         path = gtk_tree_model_get_path (model_sort, &iter_sort);
604         priv->cur_folder = folder;
605         priv->cur_row = gtk_tree_row_reference_new (model_sort, path);
606
607         /* Frees */
608         gtk_tree_path_free (path);
609
610         /* New folder has been selected */
611         g_signal_emit (G_OBJECT(tree_view), 
612                        signals[FOLDER_SELECTION_CHANGED_SIGNAL], 
613                        0, folder, TRUE); 
614 }
615
616 TnyFolder *
617 modest_folder_view_get_selected (ModestFolderView *self)
618 {
619         ModestFolderViewPrivate *priv;
620
621         g_return_val_if_fail (self, NULL);
622         
623         priv = MODEST_FOLDER_VIEW_GET_PRIVATE(self);
624         if (priv->cur_folder)
625                 g_object_ref (priv->cur_folder);
626
627         return priv->cur_folder;
628 }
629
630 static gint
631 cmp_rows (GtkTreeModel *tree_model, GtkTreeIter *iter1, GtkTreeIter *iter2,
632           gpointer user_data)
633 {
634         gint cmp;
635         gchar         *name1, *name2;
636         TnyFolderType type;
637         TnyFolder     *folder1, *folder2;
638         
639         gtk_tree_model_get (tree_model, iter1,
640                             TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN, &name1,
641                             TNY_GTK_FOLDER_STORE_TREE_MODEL_TYPE_COLUMN, &type,
642                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, &folder1,
643                             -1);
644         gtk_tree_model_get (tree_model, iter2,
645                             TNY_GTK_FOLDER_STORE_TREE_MODEL_NAME_COLUMN, &name2,
646                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, &folder2,
647                             -1);
648
649         /* local_folders should be the last one */
650         if (type == TNY_FOLDER_TYPE_ROOT) {
651                 /* the account name is also the name of the root folder
652                  * in case of local folders */
653                 if (name1 && strcmp (name1, MODEST_LOCAL_FOLDERS_ACCOUNT_NAME) == 0)
654                         cmp = +1;
655                 else if (name2 && strcmp (name2, MODEST_LOCAL_FOLDERS_ACCOUNT_NAME) == 0)
656                         cmp = -1;
657                 else 
658                         cmp = modest_text_utils_utf8_strcmp (name1, name2, TRUE);
659         } else 
660                 cmp = modest_text_utils_utf8_strcmp (name1, name2, TRUE);
661
662         
663         if (folder1)
664                 g_object_unref(G_OBJECT(folder1));
665         if (folder2)
666                 g_object_unref(G_OBJECT(folder2));
667         
668         g_free (name1);
669         g_free (name2);
670
671         return cmp;     
672 }
673
674 /*****************************************************************************/
675 /*                        DRAG and DROP stuff                                */
676 /*****************************************************************************/
677
678 /*
679  * This function fills the #GtkSelectionData with the row and the
680  * model that has been dragged. It's called when this widget is a
681  * source for dnd after the event drop happened
682  */
683 static void
684 on_drag_data_get (GtkWidget *widget, 
685                   GdkDragContext *context, 
686                   GtkSelectionData *selection_data, 
687                   guint info, 
688                   guint time, 
689                   gpointer data)
690 {
691         GtkTreeSelection *selection;
692         GtkTreeModel *model_sort, *model;
693         GtkTreeIter iter;
694         GtkTreePath *source_row_sort;
695         GtkTreePath *source_row;
696
697         selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (widget));
698         gtk_tree_selection_get_selected (selection, &model_sort, &iter);
699         source_row_sort = gtk_tree_model_get_path (model_sort, &iter);
700
701         /* Get the unsorted path and model */
702         model = gtk_tree_model_sort_get_model (GTK_TREE_MODEL_SORT (model_sort));
703         source_row = gtk_tree_model_sort_convert_path_to_child_path (GTK_TREE_MODEL_SORT (model_sort),
704                                                                      source_row_sort);
705
706         gtk_tree_set_row_drag_data (selection_data,
707                                     model,
708                                     source_row);
709
710         gtk_tree_path_free (source_row_sort);
711         gtk_tree_path_free (source_row);
712 }
713
714 typedef struct _DndHelper {
715         gboolean delete_source;
716         GtkTreePath *source_row;
717         GdkDragContext *context;
718         guint time;
719 } DndHelper;
720
721
722 /*
723  * This function is the callback of the
724  * modest_mail_operation_xfer_msg() and
725  * modest_mail_operation_xfer_folder() calls. We check here if the
726  * message/folder was correctly asynchronously transferred. The reason
727  * to use the same callback is that the code is the same, it only has
728  * to check that the operation went fine and then finalize the drag
729  * and drop action
730  */
731 static void
732 on_progress_changed (ModestMailOperation *mail_op, gpointer user_data)
733 {
734         gboolean success;
735         DndHelper *helper;
736
737         helper = (DndHelper *) user_data;
738
739         if (!modest_mail_operation_is_finished (mail_op))
740                 return;
741
742         if (modest_mail_operation_get_status (mail_op) == 
743             MODEST_MAIL_OPERATION_STATUS_SUCCESS) {
744                 success = TRUE;
745         } else {
746                 success = FALSE;
747         }
748
749         /* Notify the drag source. Never call delete, the monitor will
750            do the job if needed */
751         gtk_drag_finish (helper->context, success, FALSE, helper->time);
752
753         /* Free the helper */
754         gtk_tree_path_free (helper->source_row);        
755         g_slice_free (DndHelper, helper);
756 }
757
758 /*
759  * This function is used by drag_data_received_cb to manage drag and
760  * drop of a header, i.e, and drag from the header view to the folder
761  * view.
762  */
763 static void
764 drag_and_drop_from_header_view (GtkTreeModel *source_model,
765                                 GtkTreeModel *dest_model,
766                                 GtkTreePath  *dest_row,
767                                 DndHelper    *helper)
768 {
769         TnyHeader *header;
770         TnyFolder *folder;
771         ModestMailOperation *mail_op;
772         GtkTreeIter source_iter, dest_iter;
773
774         /* Get header */
775         gtk_tree_model_get_iter (source_model, &source_iter, helper->source_row);
776         gtk_tree_model_get (source_model, &source_iter, 
777                             TNY_GTK_HEADER_LIST_MODEL_INSTANCE_COLUMN, 
778                             &header, -1);
779
780         /* Get Folder */
781         gtk_tree_model_get_iter (dest_model, &dest_iter, dest_row);
782         gtk_tree_model_get (dest_model, &dest_iter, 
783                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, 
784                             &folder, -1);
785
786         /* Transfer message */
787         mail_op = modest_mail_operation_new ();
788         modest_mail_operation_queue_add (modest_runtime_get_mail_operation_queue (), 
789                                          mail_op);
790         g_signal_connect (G_OBJECT (mail_op), "progress-changed",
791                           G_CALLBACK (on_progress_changed), helper);
792
793         modest_mail_operation_xfer_msg (mail_op, header, folder, helper->delete_source);
794
795         /* Frees */
796         g_object_unref (G_OBJECT (mail_op));
797         g_object_unref (G_OBJECT (header));
798         g_object_unref (G_OBJECT (folder));
799 }
800
801 /*
802  * This function is used by drag_data_received_cb to manage drag and
803  * drop of a folder, i.e, and drag from the folder view to the same
804  * folder view.
805  */
806 static void
807 drag_and_drop_from_folder_view (GtkTreeModel     *source_model,
808                                 GtkTreeModel     *dest_model,
809                                 GtkTreePath      *dest_row,
810                                 GtkSelectionData *selection_data,
811                                 DndHelper        *helper)
812 {
813         ModestMailOperation *mail_op;
814         GtkTreeIter parent_iter, iter;
815         TnyFolderStore *parent_folder;
816         TnyFolder *folder;
817
818         /* Check if the drag is possible */
819         if (!gtk_tree_path_compare (helper->source_row, dest_row) ||
820             !gtk_tree_drag_dest_row_drop_possible (GTK_TREE_DRAG_DEST (dest_model),
821                                                    dest_row,
822                                                    selection_data)) {
823
824                 gtk_drag_finish (helper->context, FALSE, FALSE, helper->time);
825                 gtk_tree_path_free (helper->source_row);        
826                 g_slice_free (DndHelper, helper);
827                 return;
828         }
829
830         /* Get data */
831         gtk_tree_model_get_iter (source_model, &parent_iter, dest_row);
832         gtk_tree_model_get_iter (source_model, &iter, helper->source_row);
833         gtk_tree_model_get (source_model, &parent_iter, 
834                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN, 
835                             &parent_folder, -1);
836         gtk_tree_model_get (source_model, &iter,
837                             TNY_GTK_FOLDER_STORE_TREE_MODEL_INSTANCE_COLUMN,
838                             &folder, -1);
839
840         /* Do the mail operation */
841         mail_op = modest_mail_operation_new ();
842         modest_mail_operation_queue_add (modest_runtime_get_mail_operation_queue (), 
843                                          mail_op);
844         g_signal_connect (G_OBJECT (mail_op), "progress-changed",
845                           G_CALLBACK (on_progress_changed), helper);
846
847         modest_mail_operation_xfer_folder (mail_op, 
848                                            folder, 
849                                            parent_folder,
850                                            helper->delete_source);
851
852         /* Frees */
853         g_object_unref (G_OBJECT (parent_folder));
854         g_object_unref (G_OBJECT (folder));
855         g_object_unref (G_OBJECT (mail_op));
856 }
857
858 /*
859  * This function receives the data set by the "drag-data-get" signal
860  * handler. This information comes within the #GtkSelectionData. This
861  * function will manage both the drags of folders of the treeview and
862  * drags of headers of the header view widget.
863  */
864 static void 
865 on_drag_data_received (GtkWidget *widget, 
866                        GdkDragContext *context, 
867                        gint x, 
868                        gint y, 
869                        GtkSelectionData *selection_data, 
870                        guint target_type, 
871                        guint time, 
872                        gpointer data)
873 {
874         GtkWidget *source_widget;
875         GtkTreeModel *model_sort, *dest_model, *source_model;
876         GtkTreePath *source_row, *dest_row, *child_dest_row;
877         GtkTreeViewDropPosition pos;
878         gboolean success = FALSE, delete_source = FALSE;
879         DndHelper *helper;
880
881         /* Do not allow further process */
882         g_signal_stop_emission_by_name (widget, "drag-data-received");
883
884         /* Get the action */
885         if (context->action == GDK_ACTION_MOVE)
886                 delete_source = TRUE;
887
888         /* Check if the get_data failed */
889         if (selection_data == NULL || selection_data->length < 0)
890                 gtk_drag_finish (context, success, FALSE, time);
891
892         /* Get the models */
893         source_widget = gtk_drag_get_source_widget (context);
894         gtk_tree_get_row_drag_data (selection_data,
895                                     &source_model,
896                                     &source_row);
897
898         model_sort = gtk_tree_view_get_model (GTK_TREE_VIEW (widget));
899         /* Select the destination model */
900         if (source_widget == widget) {
901                 dest_model = source_model;
902         } else {
903                 dest_model = gtk_tree_model_sort_get_model (GTK_TREE_MODEL_SORT (model_sort));
904         }
905
906         /* Get the path to the destination row. Can not call
907            gtk_tree_view_get_drag_dest_row() because the source row
908            is not selected anymore */
909         gtk_tree_view_get_dest_row_at_pos (GTK_TREE_VIEW (widget), x, y,
910                                            &dest_row, &pos);
911
912         /* Only allow drops IN other rows */
913         if (!dest_row || pos == GTK_TREE_VIEW_DROP_BEFORE || pos == GTK_TREE_VIEW_DROP_AFTER)
914                 gtk_drag_finish (context, success, FALSE, time);
915
916         /* Create the helper */
917         helper = g_slice_new0 (DndHelper);
918         helper->delete_source = delete_source;
919         helper->source_row = gtk_tree_path_copy (source_row);
920         helper->context = context;
921         helper->time = time;
922
923         /* Get path from the unsorted model */
924         child_dest_row = 
925                 gtk_tree_model_sort_convert_path_to_child_path (GTK_TREE_MODEL_SORT (model_sort),
926                                                                 dest_row);
927         gtk_tree_path_free (dest_row);
928
929         /* Drags from the header view */
930         if (source_widget != widget) {
931
932                 drag_and_drop_from_header_view (source_model,
933                                                 dest_model,
934                                                 child_dest_row,
935                                                 helper);
936         } else {
937
938
939                 drag_and_drop_from_folder_view (source_model,
940                                                 dest_model,
941                                                 child_dest_row,
942                                                 selection_data, 
943                                                 helper);
944         }
945
946         /* Frees */
947         gtk_tree_path_free (source_row);
948         gtk_tree_path_free (child_dest_row);
949 }
950
951 /*
952  * We define a "drag-drop" signal handler because we do not want to
953  * use the default one, because the default one always calls
954  * gtk_drag_finish and we prefer to do it in the "drag-data-received"
955  * signal handler, because there we have all the information available
956  * to know if the dnd was a success or not.
957  */
958 static gboolean
959 drag_drop_cb (GtkWidget      *widget,
960               GdkDragContext *context,
961               gint            x,
962               gint            y,
963               guint           time,
964               gpointer        user_data) 
965 {
966         gpointer target;
967
968         if (!context->targets)
969                 return FALSE;
970
971         /* Check if we're dragging a folder row */
972         target = gtk_drag_dest_find_target (widget, context, NULL);
973
974         /* Request the data from the source. */
975         gtk_drag_get_data(widget, context, target, time);
976
977     return TRUE;
978 }
979
980 /*
981  * This function expands a node of a tree view if it's not expanded
982  * yet. Not sure why it needs the threads stuff, but gtk+`example code
983  * does that, so that's why they're here.
984  */
985 static gint
986 expand_row_timeout (gpointer data)
987 {
988         GtkTreeView *tree_view = data;
989         GtkTreePath *dest_path = NULL;
990         GtkTreeViewDropPosition pos;
991         gboolean result = FALSE;
992         
993         GDK_THREADS_ENTER ();
994         
995         gtk_tree_view_get_drag_dest_row (tree_view,
996                                          &dest_path,
997                                          &pos);
998         
999         if (dest_path &&
1000             (pos == GTK_TREE_VIEW_DROP_INTO_OR_AFTER ||
1001              pos == GTK_TREE_VIEW_DROP_INTO_OR_BEFORE)) {
1002                 gtk_tree_view_expand_row (tree_view, dest_path, FALSE);
1003                 gtk_tree_path_free (dest_path);
1004         }
1005         else {
1006                 if (dest_path)
1007                         gtk_tree_path_free (dest_path);
1008                 
1009                 result = TRUE;
1010         }
1011         
1012         GDK_THREADS_LEAVE ();
1013
1014         return result;
1015 }
1016
1017 /*
1018  * This function is called whenever the pointer is moved over a widget
1019  * while dragging some data. It installs a timeout that will expand a
1020  * node of the treeview if not expanded yet. This function also calls
1021  * gdk_drag_status in order to set the suggested action that will be
1022  * used by the "drag-data-received" signal handler to know if we
1023  * should do a move or just a copy of the data.
1024  */
1025 static gboolean
1026 on_drag_motion (GtkWidget      *widget,
1027                 GdkDragContext *context,
1028                 gint            x,
1029                 gint            y,
1030                 guint           time,
1031                 gpointer        user_data)  
1032 {
1033         GtkTreeViewDropPosition pos;
1034         GtkTreePath *dest_row;
1035         ModestFolderViewPrivate *priv;
1036         GdkDragAction suggested_action;
1037         gboolean valid_location = FALSE;
1038
1039         priv = MODEST_FOLDER_VIEW_GET_PRIVATE (widget);
1040
1041         if (priv->timer_expander != 0) {
1042                 g_source_remove (priv->timer_expander);
1043                 priv->timer_expander = 0;
1044         }
1045
1046         gtk_tree_view_get_dest_row_at_pos (GTK_TREE_VIEW (widget),
1047                                            x, y,
1048                                            &dest_row,
1049                                            &pos);
1050
1051         /* Do not allow drops between folders */
1052         if (!dest_row ||
1053             pos == GTK_TREE_VIEW_DROP_BEFORE || 
1054             pos == GTK_TREE_VIEW_DROP_AFTER) {
1055                 gtk_tree_view_set_drag_dest_row(GTK_TREE_VIEW (widget), NULL, 0);
1056                 gdk_drag_status(context, 0, time);
1057                 valid_location = FALSE;
1058                 goto out;
1059         } else {
1060                 valid_location = TRUE;
1061         }
1062
1063         /* Expand the selected row after 1/2 second */
1064         if (!gtk_tree_view_row_expanded (GTK_TREE_VIEW (widget), dest_row)) {
1065                 gtk_tree_view_set_drag_dest_row (GTK_TREE_VIEW (widget), dest_row, pos);
1066                 priv->timer_expander = g_timeout_add (500, expand_row_timeout, widget);
1067         }
1068         gtk_tree_path_free (dest_row);
1069
1070         /* Select the desired action. By default we pick MOVE */
1071         suggested_action = GDK_ACTION_MOVE;
1072
1073         if (context->actions == GDK_ACTION_COPY)
1074             gdk_drag_status(context, GDK_ACTION_COPY, time);
1075         else if (context->actions == GDK_ACTION_MOVE)
1076             gdk_drag_status(context, GDK_ACTION_MOVE, time);
1077         else if (context->actions & suggested_action)
1078             gdk_drag_status(context, suggested_action, time);
1079         else
1080             gdk_drag_status(context, GDK_ACTION_DEFAULT, time);
1081
1082  out:
1083         g_signal_stop_emission_by_name (widget, "drag-motion");
1084         return valid_location;
1085 }
1086
1087
1088 /* Folder view drag types */
1089 const GtkTargetEntry folder_view_drag_types[] =
1090 {
1091         { "GTK_TREE_MODEL_ROW", GTK_TARGET_SAME_WIDGET, MODEST_FOLDER_ROW },
1092         { "GTK_TREE_MODEL_ROW", GTK_TARGET_SAME_APP,    MODEST_HEADER_ROW }
1093 };
1094
1095 /*
1096  * This function sets the treeview as a source and a target for dnd
1097  * events. It also connects all the requirede signals.
1098  */
1099 static void
1100 setup_drag_and_drop (GtkTreeView *self)
1101 {
1102         /* Set up the folder view as a dnd destination. Set only the
1103            highlight flag, otherwise gtk will have a different
1104            behaviour */
1105         gtk_drag_dest_set (GTK_WIDGET (self),
1106                            GTK_DEST_DEFAULT_HIGHLIGHT,
1107                            folder_view_drag_types,
1108                            G_N_ELEMENTS (folder_view_drag_types),
1109                            GDK_ACTION_MOVE | GDK_ACTION_COPY);
1110
1111         g_signal_connect (G_OBJECT (self),
1112                           "drag_data_received",
1113                           G_CALLBACK (on_drag_data_received),
1114                           NULL);
1115
1116
1117         /* Set up the treeview as a dnd source */
1118         gtk_drag_source_set (GTK_WIDGET (self),
1119                              GDK_BUTTON1_MASK,
1120                              folder_view_drag_types,
1121                              G_N_ELEMENTS (folder_view_drag_types),
1122                              GDK_ACTION_MOVE | GDK_ACTION_COPY);
1123
1124         g_signal_connect (G_OBJECT (self),
1125                           "drag_motion",
1126                           G_CALLBACK (on_drag_motion),
1127                           NULL);
1128         
1129         g_signal_connect (G_OBJECT (self),
1130                           "drag_data_get",
1131                           G_CALLBACK (on_drag_data_get),
1132                           NULL);
1133
1134         g_signal_connect (G_OBJECT (self),
1135                           "drag_drop",
1136                           G_CALLBACK (drag_drop_cb),
1137                           NULL);
1138 }