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