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