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