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