Properly calculate the MyDocs folder paths.
[modest] / src / hildon2 / modest-msg-view-window.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 #include <glib/gi18n.h>
30 #include <string.h>
31 #include <tny-account-store.h>
32 #include <tny-simple-list.h>
33 #include <tny-msg.h>
34 #include <tny-mime-part.h>
35 #include <tny-vfs-stream.h>
36 #include "modest-marshal.h"
37 #include "modest-platform.h"
38 #include <modest-utils.h>
39 #include <modest-maemo-utils.h>
40 #include <modest-tny-msg.h>
41 #include <modest-msg-view-window.h>
42 #include <modest-main-window-ui.h>
43 #include "modest-msg-view-window-ui-dimming.h"
44 #include <modest-widget-memory.h>
45 #include <modest-progress-object.h>
46 #include <modest-runtime.h>
47 #include <modest-window-priv.h>
48 #include <modest-tny-folder.h>
49 #include <modest-text-utils.h>
50 #include <modest-account-mgr-helpers.h>
51 #include <hildon/hildon-pannable-area.h>
52 #include <hildon/hildon-picker-dialog.h>
53 #include <hildon/hildon-app-menu.h>
54 #include "modest-defs.h"
55 #include "modest-hildon-includes.h"
56 #include "modest-ui-dimming-manager.h"
57 #include <gdk/gdkkeysyms.h>
58 #include <modest-tny-account.h>
59 #include <modest-mime-part-view.h>
60 #include <modest-isearch-view.h>
61 #include <modest-tny-mime-part.h>
62 #include <modest-address-book.h>
63 #include <math.h>
64 #include <errno.h>
65 #include <glib/gstdio.h>
66 #include <modest-debug.h>
67 #include <modest-header-window.h>
68
69 #define MYDOCS_ENV "MYDOCSDIR"
70 #define DOCS_FOLDER ".documents"
71
72 typedef struct _ModestMsgViewWindowPrivate ModestMsgViewWindowPrivate;
73 struct _ModestMsgViewWindowPrivate {
74
75         GtkWidget   *msg_view;
76         GtkWidget   *main_scroll;
77         GtkWidget   *find_toolbar;
78         gchar       *last_search;
79
80         /* Progress observers */
81         GSList           *progress_widgets;
82
83         /* Tollbar items */
84         GtkWidget   *prev_toolitem;
85         GtkWidget   *next_toolitem;
86         gboolean    progress_hint;
87
88         /* Optimized view enabled */
89         gboolean optimized_view;
90
91         /* Whether this was created via the *_new_for_search_result() function. */
92         gboolean is_search_result;
93
94         /* Whether the message is in outbox */
95         gboolean is_outbox;
96         
97         /* A reference to the @model of the header view 
98          * to allow selecting previous/next messages,
99          * if the message is currently selected in the header view.
100          */
101         const gchar *header_folder_id;
102         GtkTreeModel *header_model;
103         GtkTreeRowReference *row_reference;
104         GtkTreeRowReference *next_row_reference;
105
106         gulong clipboard_change_handler;
107         gulong queue_change_handler;
108         gulong account_removed_handler;
109         gulong row_changed_handler;
110         gulong row_deleted_handler;
111         gulong row_inserted_handler;
112         gulong rows_reordered_handler;
113
114         guint purge_timeout;
115         GtkWidget *remove_attachment_banner;
116
117         gchar *msg_uid;
118         
119         GSList *sighandlers;
120 };
121
122 static void  modest_msg_view_window_class_init   (ModestMsgViewWindowClass *klass);
123 static void  modest_msg_view_window_init         (ModestMsgViewWindow *obj);
124 static void  modest_header_view_observer_init(
125                 ModestHeaderViewObserverIface *iface_class);
126 static void  modest_msg_view_window_finalize     (GObject *obj);
127 static void  modest_msg_view_window_toggle_find_toolbar (GtkToggleAction *obj,
128                                                          gpointer data);
129 static void  modest_msg_view_window_find_toolbar_close (GtkWidget *widget,
130                                                         ModestMsgViewWindow *obj);
131 static void  modest_msg_view_window_find_toolbar_search (GtkWidget *widget,
132                                                         ModestMsgViewWindow *obj);
133
134 static void modest_msg_view_window_disconnect_signals (ModestWindow *self);
135
136 static gdouble modest_msg_view_window_get_zoom (ModestWindow *window);
137 static void modest_msg_view_window_set_zoom (ModestWindow *window,
138                                              gdouble zoom);
139 static gboolean modest_msg_view_window_zoom_minus (ModestWindow *window);
140 static gboolean modest_msg_view_window_zoom_plus (ModestWindow *window);
141 static gboolean modest_msg_view_window_key_event (GtkWidget *window,
142                                                   GdkEventKey *event,
143                                                   gpointer userdata);
144 static void modest_msg_view_window_update_priority (ModestMsgViewWindow *window);
145
146 static void modest_msg_view_window_show_toolbar   (ModestWindow *window,
147                                                    gboolean show_toolbar);
148
149 static void modest_msg_view_window_clipboard_owner_change (GtkClipboard *clipboard,
150                                                            GdkEvent *event,
151                                                            ModestMsgViewWindow *window);
152
153 static void modest_msg_view_window_on_row_changed (GtkTreeModel *header_model,
154                                                    GtkTreePath *arg1,
155                                                    GtkTreeIter *arg2,
156                                                    ModestMsgViewWindow *window);
157
158 static void modest_msg_view_window_on_row_deleted (GtkTreeModel *header_model,
159                                                    GtkTreePath *arg1,
160                                                    ModestMsgViewWindow *window);
161
162 static void modest_msg_view_window_on_row_inserted (GtkTreeModel *header_model,
163                                                     GtkTreePath *tree_path,
164                                                     GtkTreeIter *tree_iter,
165                                                     ModestMsgViewWindow *window);
166
167 static void modest_msg_view_window_on_row_reordered (GtkTreeModel *header_model,
168                                                      GtkTreePath *arg1,
169                                                      GtkTreeIter *arg2,
170                                                      gpointer arg3,
171                                                      ModestMsgViewWindow *window);
172
173 static void modest_msg_view_window_update_model_replaced (ModestHeaderViewObserver *window,
174                                                           GtkTreeModel *model,
175                                                           const gchar *tny_folder_id);
176
177 static void on_queue_changed    (ModestMailOperationQueue *queue,
178                                  ModestMailOperation *mail_op,
179                                  ModestMailOperationQueueNotification type,
180                                  ModestMsgViewWindow *self);
181
182 static void on_account_removed  (TnyAccountStore *account_store, 
183                                  TnyAccount *account,
184                                  gpointer user_data);
185
186 static void on_move_focus (GtkWidget *widget,
187                            GtkDirectionType direction,
188                            gpointer userdata);
189
190 static void view_msg_cb         (ModestMailOperation *mail_op, 
191                                  TnyHeader *header, 
192                                  gboolean canceled,
193                                  TnyMsg *msg, 
194                                  GError *error,
195                                  gpointer user_data);
196
197 static void set_progress_hint    (ModestMsgViewWindow *self, 
198                                   gboolean enabled);
199
200 static void update_window_title (ModestMsgViewWindow *window);
201
202 static gboolean set_toolbar_transfer_mode     (ModestMsgViewWindow *self); 
203 static void init_window (ModestMsgViewWindow *obj);
204
205 static gboolean msg_is_visible (TnyHeader *header, gboolean check_outbox);
206
207 static void check_dimming_rules_after_change (ModestMsgViewWindow *window);
208
209 static gboolean on_fetch_image (ModestMsgView *msgview,
210                                 const gchar *uri,
211                                 TnyStream *stream,
212                                 ModestMsgViewWindow *window);
213
214 static gboolean modest_msg_view_window_scroll_child (ModestMsgViewWindow *self,
215                                                      GtkScrollType scroll_type,
216                                                      gboolean horizontal,
217                                                      gpointer userdata);
218 static gboolean message_reader (ModestMsgViewWindow *window,
219                                 ModestMsgViewWindowPrivate *priv,
220                                 TnyHeader *header,
221                                 GtkTreeRowReference *row_reference);
222
223 static void setup_menu (ModestMsgViewWindow *self);
224
225 /* list my signals */
226 enum {
227         MSG_CHANGED_SIGNAL,
228         SCROLL_CHILD_SIGNAL,
229         LAST_SIGNAL
230 };
231
232 static const GtkToggleActionEntry msg_view_toggle_action_entries [] = {
233         { "FindInMessage",    MODEST_TOOLBAR_ICON_FIND,    N_("qgn_toolb_gene_find"), NULL, NULL, G_CALLBACK (modest_msg_view_window_toggle_find_toolbar), FALSE },
234 };
235
236
237 #define MODEST_MSG_VIEW_WINDOW_GET_PRIVATE(o)      (G_TYPE_INSTANCE_GET_PRIVATE((o), \
238                                                     MODEST_TYPE_MSG_VIEW_WINDOW, \
239                                                     ModestMsgViewWindowPrivate))
240 /* globals */
241 static GtkWindowClass *parent_class = NULL;
242
243 /* uncomment the following if you have defined any signals */
244 static guint signals[LAST_SIGNAL] = {0};
245
246 GType
247 modest_msg_view_window_get_type (void)
248 {
249         static GType my_type = 0;
250         if (!my_type) {
251                 static const GTypeInfo my_info = {
252                         sizeof(ModestMsgViewWindowClass),
253                         NULL,           /* base init */
254                         NULL,           /* base finalize */
255                         (GClassInitFunc) modest_msg_view_window_class_init,
256                         NULL,           /* class finalize */
257                         NULL,           /* class data */
258                         sizeof(ModestMsgViewWindow),
259                         1,              /* n_preallocs */
260                         (GInstanceInitFunc) modest_msg_view_window_init,
261                         NULL
262                 };
263                 my_type = g_type_register_static (MODEST_TYPE_HILDON2_WINDOW,
264                                                   "ModestMsgViewWindow",
265                                                   &my_info, 0);
266
267                 static const GInterfaceInfo modest_header_view_observer_info = 
268                 {
269                         (GInterfaceInitFunc) modest_header_view_observer_init,
270                         NULL,         /* interface_finalize */
271                         NULL          /* interface_data */
272                 };
273
274                 g_type_add_interface_static (my_type,
275                                 MODEST_TYPE_HEADER_VIEW_OBSERVER,
276                                 &modest_header_view_observer_info);
277         }
278         return my_type;
279 }
280
281 static void
282 save_state (ModestWindow *self)
283 {
284         modest_widget_memory_save (modest_runtime_get_conf (),
285                                    G_OBJECT(self), 
286                                    MODEST_CONF_MSG_VIEW_WINDOW_KEY);
287 }
288
289 static 
290 gboolean modest_msg_view_window_scroll_child (ModestMsgViewWindow *self,
291                                               GtkScrollType scroll_type,
292                                               gboolean horizontal,
293                                               gpointer userdata)
294 {
295         ModestMsgViewWindowPrivate *priv;
296         gboolean return_value;
297
298         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE(self);
299         g_signal_emit_by_name (priv->main_scroll, "scroll-child", scroll_type, horizontal, &return_value);
300         return return_value;
301 }
302
303 static void
304 add_scroll_binding (GtkBindingSet *binding_set,
305                     guint keyval,
306                     GtkScrollType scroll)
307 {
308         guint keypad_keyval = keyval - GDK_Left + GDK_KP_Left;
309         
310         gtk_binding_entry_add_signal (binding_set, keyval, 0,
311                                       "scroll_child", 2,
312                                       GTK_TYPE_SCROLL_TYPE, scroll,
313                                       G_TYPE_BOOLEAN, FALSE);
314         gtk_binding_entry_add_signal (binding_set, keypad_keyval, 0,
315                                       "scroll_child", 2,
316                                       GTK_TYPE_SCROLL_TYPE, scroll,
317                                       G_TYPE_BOOLEAN, FALSE);
318 }
319
320 static void
321 modest_msg_view_window_class_init (ModestMsgViewWindowClass *klass)
322 {
323         GObjectClass *gobject_class;
324         HildonWindowClass *hildon_window_class;
325         ModestWindowClass *modest_window_class;
326         GtkBindingSet *binding_set;
327
328         gobject_class = (GObjectClass*) klass;
329         hildon_window_class = (HildonWindowClass *) klass;
330         modest_window_class = (ModestWindowClass *) klass;
331
332         parent_class            = g_type_class_peek_parent (klass);
333         gobject_class->finalize = modest_msg_view_window_finalize;
334
335         modest_window_class->set_zoom_func = modest_msg_view_window_set_zoom;
336         modest_window_class->get_zoom_func = modest_msg_view_window_get_zoom;
337         modest_window_class->zoom_plus_func = modest_msg_view_window_zoom_plus;
338         modest_window_class->zoom_minus_func = modest_msg_view_window_zoom_minus;
339         modest_window_class->show_toolbar_func = modest_msg_view_window_show_toolbar;
340         modest_window_class->disconnect_signals_func = modest_msg_view_window_disconnect_signals;
341
342         modest_window_class->save_state_func = save_state;
343
344         klass->scroll_child = modest_msg_view_window_scroll_child;
345
346         signals[MSG_CHANGED_SIGNAL] =
347                 g_signal_new ("msg-changed",
348                               G_TYPE_FROM_CLASS (gobject_class),
349                               G_SIGNAL_RUN_FIRST,
350                               G_STRUCT_OFFSET (ModestMsgViewWindowClass, msg_changed),
351                               NULL, NULL,
352                               modest_marshal_VOID__POINTER_POINTER,
353                               G_TYPE_NONE, 2, G_TYPE_POINTER, G_TYPE_POINTER);
354
355         signals[SCROLL_CHILD_SIGNAL] =
356                 g_signal_new ("scroll-child",
357                               G_TYPE_FROM_CLASS (gobject_class),
358                               G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
359                               G_STRUCT_OFFSET (ModestMsgViewWindowClass, scroll_child),
360                               NULL, NULL,
361                               modest_marshal_BOOLEAN__ENUM_BOOLEAN,
362                               G_TYPE_BOOLEAN, 2, GTK_TYPE_SCROLL_TYPE, G_TYPE_BOOLEAN);
363
364         binding_set = gtk_binding_set_by_class (klass);
365         add_scroll_binding (binding_set, GDK_Up, GTK_SCROLL_STEP_UP);
366         add_scroll_binding (binding_set, GDK_Down, GTK_SCROLL_STEP_DOWN);
367         add_scroll_binding (binding_set, GDK_Page_Up, GTK_SCROLL_PAGE_UP);
368         add_scroll_binding (binding_set, GDK_Page_Down, GTK_SCROLL_PAGE_DOWN);
369         add_scroll_binding (binding_set, GDK_Home, GTK_SCROLL_START);
370         add_scroll_binding (binding_set, GDK_End, GTK_SCROLL_END);
371
372         g_type_class_add_private (gobject_class, sizeof(ModestMsgViewWindowPrivate));
373
374 }
375
376 static void modest_header_view_observer_init(
377                 ModestHeaderViewObserverIface *iface_class)
378 {
379         iface_class->update_func = modest_msg_view_window_update_model_replaced;
380 }
381
382 static void
383 modest_msg_view_window_init (ModestMsgViewWindow *obj)
384 {
385         ModestMsgViewWindowPrivate *priv;
386         ModestWindowPrivate *parent_priv = NULL;
387         GtkActionGroup *action_group = NULL;
388         GError *error = NULL;
389         GdkPixbuf *window_icon;
390
391         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE(obj);
392         parent_priv = MODEST_WINDOW_GET_PRIVATE(obj);
393         parent_priv->ui_manager = gtk_ui_manager_new();
394
395         action_group = gtk_action_group_new ("ModestMsgViewWindowActions");
396         gtk_action_group_set_translation_domain (action_group, GETTEXT_PACKAGE);
397
398         /* Add common actions */
399         gtk_action_group_add_actions (action_group,
400                                       modest_action_entries,
401                                       G_N_ELEMENTS (modest_action_entries),
402                                       obj);
403         gtk_action_group_add_toggle_actions (action_group,
404                                              msg_view_toggle_action_entries,
405                                              G_N_ELEMENTS (msg_view_toggle_action_entries),
406                                              obj);
407
408         gtk_ui_manager_insert_action_group (parent_priv->ui_manager, action_group, 0);
409         g_object_unref (action_group);
410
411         /* Load the UI definition */
412         gtk_ui_manager_add_ui_from_file (parent_priv->ui_manager, MODEST_UIDIR "modest-msg-view-window-ui.xml",
413                                          &error);
414         if (error) {
415                 g_printerr ("modest: could not merge modest-msg-view-window-ui.xml: %s\n", error->message);
416                 g_error_free (error);
417                 error = NULL;
418         }
419         /* ****** */
420
421         /* Add accelerators */
422         gtk_window_add_accel_group (GTK_WINDOW (obj), 
423                                     gtk_ui_manager_get_accel_group (parent_priv->ui_manager));
424         
425         priv->is_search_result = FALSE;
426         priv->is_outbox = FALSE;
427
428         priv->msg_view      = NULL;
429         priv->header_model  = NULL;
430         priv->header_folder_id  = NULL;
431         priv->clipboard_change_handler = 0;
432         priv->queue_change_handler = 0;
433         priv->account_removed_handler = 0;
434         priv->row_changed_handler = 0;
435         priv->row_deleted_handler = 0;
436         priv->row_inserted_handler = 0;
437         priv->rows_reordered_handler = 0;
438         priv->progress_hint = FALSE;
439
440         priv->optimized_view  = FALSE;
441         priv->purge_timeout = 0;
442         priv->remove_attachment_banner = NULL;
443         priv->msg_uid = NULL;
444         
445         priv->sighandlers = NULL;
446         
447         /* Init window */
448         init_window (MODEST_MSG_VIEW_WINDOW(obj));
449         
450         /* Set window icon */
451         window_icon = modest_platform_get_icon (MODEST_APP_MSG_VIEW_ICON, MODEST_ICON_SIZE_BIG); 
452         if (window_icon) {
453                 gtk_window_set_icon (GTK_WINDOW (obj), window_icon);
454                 g_object_unref (window_icon);
455         }       
456         
457         hildon_program_add_window (hildon_program_get_instance(),
458                                    HILDON_WINDOW(obj));
459
460 }
461
462
463 static gboolean
464 set_toolbar_transfer_mode (ModestMsgViewWindow *self)
465 {
466         ModestMsgViewWindowPrivate *priv = NULL;
467         
468         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (self), FALSE);
469
470         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE(self);
471
472         set_progress_hint (self, TRUE);
473         
474         return FALSE;
475 }
476
477 static void 
478 set_progress_hint (ModestMsgViewWindow *self, 
479                    gboolean enabled)
480 {
481         ModestWindowPrivate *parent_priv;
482         ModestMsgViewWindowPrivate *priv;
483
484         g_return_if_fail (MODEST_IS_MSG_VIEW_WINDOW (self));
485
486         parent_priv = MODEST_WINDOW_GET_PRIVATE(self);
487         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE(self);
488                         
489         /* Sets current progress hint */
490         priv->progress_hint = enabled;
491
492         if (GTK_WIDGET_VISIBLE (self)) {
493                 hildon_gtk_window_set_progress_indicator (GTK_WINDOW (self), enabled?1:0);
494         }
495
496 }
497
498
499 static void
500 init_window (ModestMsgViewWindow *obj)
501 {
502         GtkWidget *main_vbox;
503         ModestMsgViewWindowPrivate *priv;
504
505         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE(obj);
506
507         priv->msg_view = GTK_WIDGET (tny_platform_factory_new_msg_view (modest_tny_platform_factory_get_instance ()));
508         modest_msg_view_set_shadow_type (MODEST_MSG_VIEW (priv->msg_view), GTK_SHADOW_NONE);
509         main_vbox = gtk_vbox_new  (FALSE, 6);
510 #ifdef MODEST_TOOLKIT_HILDON2
511         priv->main_scroll = hildon_pannable_area_new ();
512         gtk_container_add (GTK_CONTAINER (priv->main_scroll), priv->msg_view);
513 #else
514 #ifdef MODEST_USE_MOZEMBED
515         priv->main_scroll = priv->msg_view;
516         gtk_widget_set_size_request (priv->msg_view, -1, 1600);
517 #else
518         priv->main_scroll = gtk_scrolled_window_new (NULL, NULL);
519         gtk_container_add (GTK_CONTAINER (priv->main_scroll), priv->msg_view);
520 #endif
521         gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (priv->main_scroll), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
522         gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (priv->main_scroll), GTK_SHADOW_NONE);
523         modest_maemo_set_thumbable_scrollbar (GTK_SCROLLED_WINDOW(priv->main_scroll), TRUE);
524
525 #endif
526         gtk_box_pack_start (GTK_BOX(main_vbox), priv->main_scroll, TRUE, TRUE, 0);
527         gtk_container_add   (GTK_CONTAINER(obj), main_vbox);
528
529         priv->find_toolbar = hildon_find_toolbar_new (NULL);
530         hildon_window_add_toolbar (HILDON_WINDOW (obj), GTK_TOOLBAR (priv->find_toolbar));
531         gtk_widget_set_no_show_all (priv->find_toolbar, TRUE);
532         
533         gtk_widget_show_all (GTK_WIDGET(main_vbox));
534 }
535
536 static void
537 modest_msg_view_window_disconnect_signals (ModestWindow *self)
538 {
539         ModestMsgViewWindowPrivate *priv;
540         GtkWidget *header_view = NULL;
541         GtkWindow *parent_window = NULL;
542         
543         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (self);
544
545         if (gtk_clipboard_get (GDK_SELECTION_PRIMARY) &&
546             g_signal_handler_is_connected (gtk_clipboard_get (GDK_SELECTION_PRIMARY),
547                                            priv->clipboard_change_handler)) 
548                 g_signal_handler_disconnect (gtk_clipboard_get (GDK_SELECTION_PRIMARY), 
549                                              priv->clipboard_change_handler);
550
551         if (g_signal_handler_is_connected (G_OBJECT (modest_runtime_get_mail_operation_queue ()), 
552                                            priv->queue_change_handler))
553                 g_signal_handler_disconnect (G_OBJECT (modest_runtime_get_mail_operation_queue ()), 
554                                              priv->queue_change_handler);
555
556         if (g_signal_handler_is_connected (G_OBJECT (modest_runtime_get_account_store ()), 
557                                            priv->account_removed_handler))
558                 g_signal_handler_disconnect (G_OBJECT (modest_runtime_get_account_store ()), 
559                                              priv->account_removed_handler);
560
561         if (priv->header_model) {
562                 if (g_signal_handler_is_connected(G_OBJECT (priv->header_model), 
563                                                   priv->row_changed_handler))
564                         g_signal_handler_disconnect(G_OBJECT (priv->header_model), 
565                                                     priv->row_changed_handler);
566                 
567                 if (g_signal_handler_is_connected(G_OBJECT (priv->header_model), 
568                                                   priv->row_deleted_handler))
569                         g_signal_handler_disconnect(G_OBJECT (priv->header_model), 
570                                              priv->row_deleted_handler);
571                 
572                 if (g_signal_handler_is_connected(G_OBJECT (priv->header_model), 
573                                                   priv->row_inserted_handler))
574                         g_signal_handler_disconnect(G_OBJECT (priv->header_model), 
575                                                     priv->row_inserted_handler);
576                 
577                 if (g_signal_handler_is_connected(G_OBJECT (priv->header_model), 
578                                                   priv->rows_reordered_handler))
579                         g_signal_handler_disconnect(G_OBJECT (priv->header_model), 
580                                                     priv->rows_reordered_handler);
581         }
582
583         modest_signal_mgr_disconnect_all_and_destroy (priv->sighandlers);
584         priv->sighandlers = NULL;
585
586         parent_window = gtk_window_get_transient_for (GTK_WINDOW (self));
587         if (parent_window && MODEST_IS_HEADER_WINDOW (parent_window)) {
588                 header_view = GTK_WIDGET (modest_header_window_get_header_view (MODEST_HEADER_WINDOW (parent_window)));
589                 if (header_view) {
590                         modest_header_view_remove_observer(MODEST_HEADER_VIEW (header_view),
591                                                            MODEST_HEADER_VIEW_OBSERVER(self));
592                 }
593         }
594 }       
595
596 static void
597 modest_msg_view_window_finalize (GObject *obj)
598 {
599         ModestMsgViewWindowPrivate *priv;
600
601         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (obj);
602
603         /* Sanity check: shouldn't be needed, the window mgr should
604            call this function before */
605         modest_msg_view_window_disconnect_signals (MODEST_WINDOW (obj));
606
607         if (priv->header_model != NULL) {
608                 g_object_unref (priv->header_model);
609                 priv->header_model = NULL;
610         }
611
612         if (priv->remove_attachment_banner) {
613                 gtk_widget_destroy (priv->remove_attachment_banner);
614                 g_object_unref (priv->remove_attachment_banner);
615                 priv->remove_attachment_banner = NULL;
616         }
617
618         if (priv->purge_timeout > 0) {
619                 g_source_remove (priv->purge_timeout);
620                 priv->purge_timeout = 0;
621         }
622
623         if (priv->row_reference) {
624                 gtk_tree_row_reference_free (priv->row_reference);
625                 priv->row_reference = NULL;
626         }
627
628         if (priv->next_row_reference) {
629                 gtk_tree_row_reference_free (priv->next_row_reference);
630                 priv->next_row_reference = NULL;
631         }
632
633         if (priv->msg_uid) {
634                 g_free (priv->msg_uid);
635                 priv->msg_uid = NULL;
636         }
637
638         G_OBJECT_CLASS(parent_class)->finalize (obj);
639 }
640
641 static gboolean
642 select_next_valid_row (GtkTreeModel *model,
643                        GtkTreeRowReference **row_reference,
644                        gboolean cycle,
645                        gboolean is_outbox)
646 {
647         GtkTreeIter tmp_iter;
648         GtkTreePath *path;
649         GtkTreePath *next = NULL;
650         gboolean retval = FALSE, finished;
651
652         g_return_val_if_fail (gtk_tree_row_reference_valid (*row_reference), FALSE);
653
654         path = gtk_tree_row_reference_get_path (*row_reference);
655         gtk_tree_model_get_iter (model, &tmp_iter, path);
656         gtk_tree_row_reference_free (*row_reference);
657         *row_reference = NULL;
658
659         finished = FALSE;
660         do {
661                 TnyHeader *header = NULL;
662
663                 if (gtk_tree_model_iter_next (model, &tmp_iter)) {
664                         gtk_tree_model_get (model, &tmp_iter, 
665                                             TNY_GTK_HEADER_LIST_MODEL_INSTANCE_COLUMN, 
666                                             &header, -1);
667
668                         if (header) {
669                                 if (msg_is_visible (header, is_outbox)) {
670                                         next = gtk_tree_model_get_path (model, &tmp_iter);
671                                         *row_reference = gtk_tree_row_reference_new (model, next);
672                                         gtk_tree_path_free (next);
673                                         retval = TRUE;
674                                         finished = TRUE;
675                                 }
676                                 g_object_unref (header);
677                                 header = NULL;
678                         }
679                 } else if (cycle && gtk_tree_model_get_iter_first (model, &tmp_iter)) {
680                         next = gtk_tree_model_get_path (model, &tmp_iter);
681                         
682                         /* Ensure that we are not selecting the same */
683                         if (gtk_tree_path_compare (path, next) != 0) {
684                                 gtk_tree_model_get (model, &tmp_iter, 
685                                                     TNY_GTK_HEADER_LIST_MODEL_INSTANCE_COLUMN, 
686                                                     &header, -1);                               
687                                 if (header) {
688                                         if (msg_is_visible (header, is_outbox)) {
689                                                 *row_reference = gtk_tree_row_reference_new (model, next);
690                                                 retval = TRUE;
691                                                 finished = TRUE;
692                                         }
693                                         g_object_unref (header);
694                                         header = NULL;
695                                 }
696                         } else {
697                                 /* If we ended up in the same message
698                                    then there is no valid next
699                                    message */
700                                 finished = TRUE;
701                         }
702                         gtk_tree_path_free (next);
703                 } else {
704                         /* If there are no more messages and we don't
705                            want to start again in the first one then
706                            there is no valid next message */
707                         finished = TRUE;
708                 }
709         } while (!finished);
710
711         /* Free */
712         gtk_tree_path_free (path);
713
714         return retval;
715 }
716
717 /* TODO: This should be in _init(), with the parameters as properties. */
718 static void
719 modest_msg_view_window_construct (ModestMsgViewWindow *self, 
720                                   const gchar *modest_account_name,
721                                   const gchar *msg_uid)
722 {
723         GObject *obj = NULL;
724         ModestMsgViewWindowPrivate *priv = NULL;
725         ModestWindowPrivate *parent_priv = NULL;
726         ModestDimmingRulesGroup *toolbar_rules_group = NULL;
727         ModestDimmingRulesGroup *clipboard_rules_group = NULL;
728
729         obj = G_OBJECT (self);
730         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE(obj);
731         parent_priv = MODEST_WINDOW_GET_PRIVATE(obj);
732
733         priv->msg_uid = g_strdup (msg_uid);
734
735         /* Menubar */
736         parent_priv->menubar = NULL;
737
738         toolbar_rules_group = modest_dimming_rules_group_new (MODEST_DIMMING_RULES_TOOLBAR, TRUE);
739         clipboard_rules_group = modest_dimming_rules_group_new (MODEST_DIMMING_RULES_CLIPBOARD, FALSE);
740
741         setup_menu (self);
742         /* Add common dimming rules */
743         modest_dimming_rules_group_add_rules (toolbar_rules_group, 
744                                               modest_msg_view_toolbar_dimming_entries,
745                                               G_N_ELEMENTS (modest_msg_view_toolbar_dimming_entries),
746                                               MODEST_WINDOW (self));
747         modest_dimming_rules_group_add_rules (clipboard_rules_group, 
748                                               modest_msg_view_clipboard_dimming_entries,
749                                               G_N_ELEMENTS (modest_msg_view_clipboard_dimming_entries),
750                                               MODEST_WINDOW (self));
751
752         /* Insert dimming rules group for this window */
753         modest_ui_dimming_manager_insert_rules_group (parent_priv->ui_dimming_manager, toolbar_rules_group);
754         modest_ui_dimming_manager_insert_rules_group (parent_priv->ui_dimming_manager, clipboard_rules_group);
755         g_object_unref (toolbar_rules_group);
756         g_object_unref (clipboard_rules_group);
757
758         /* g_signal_connect (G_OBJECT(obj), "delete-event", G_CALLBACK(on_delete_event), obj); */
759
760         priv->clipboard_change_handler = g_signal_connect (G_OBJECT (gtk_clipboard_get (GDK_SELECTION_PRIMARY)), "owner-change", G_CALLBACK (modest_msg_view_window_clipboard_owner_change), obj);
761         g_signal_connect (G_OBJECT(priv->msg_view), "activate_link",
762                           G_CALLBACK (modest_ui_actions_on_msg_link_clicked), obj);
763         g_signal_connect (G_OBJECT(priv->msg_view), "link_hover",
764                           G_CALLBACK (modest_ui_actions_on_msg_link_hover), obj);
765         g_signal_connect (G_OBJECT(priv->msg_view), "attachment_clicked",
766                           G_CALLBACK (modest_ui_actions_on_msg_attachment_clicked), obj);
767         g_signal_connect (G_OBJECT(priv->msg_view), "recpt_activated",
768                           G_CALLBACK (modest_ui_actions_on_msg_recpt_activated), obj);
769         g_signal_connect (G_OBJECT(priv->msg_view), "show_details",
770                           G_CALLBACK (modest_ui_actions_on_details), obj);
771         g_signal_connect (G_OBJECT(priv->msg_view), "link_contextual",
772                           G_CALLBACK (modest_ui_actions_on_msg_link_contextual), obj);
773         g_signal_connect (G_OBJECT (priv->msg_view), "fetch_image",
774                           G_CALLBACK (on_fetch_image), obj);
775
776         g_signal_connect (G_OBJECT (obj), "key-release-event",
777                           G_CALLBACK (modest_msg_view_window_key_event),
778                           NULL);
779
780         g_signal_connect (G_OBJECT (obj), "key-press-event",
781                           G_CALLBACK (modest_msg_view_window_key_event),
782                           NULL);
783
784         g_signal_connect (G_OBJECT (obj), "move-focus",
785                           G_CALLBACK (on_move_focus), obj);
786
787         /* Mail Operation Queue */
788         priv->queue_change_handler = g_signal_connect (G_OBJECT (modest_runtime_get_mail_operation_queue ()),
789                                                        "queue-changed",
790                                                        G_CALLBACK (on_queue_changed),
791                                                        obj);
792
793         /* Account manager */
794         priv->account_removed_handler = g_signal_connect (G_OBJECT (modest_runtime_get_account_store ()),
795                                                           "account_removed",
796                                                           G_CALLBACK(on_account_removed),
797                                                           obj);
798
799         modest_window_set_active_account (MODEST_WINDOW(obj), modest_account_name);
800
801         g_signal_connect (G_OBJECT (priv->find_toolbar), "close", G_CALLBACK (modest_msg_view_window_find_toolbar_close), obj);
802         g_signal_connect (G_OBJECT (priv->find_toolbar), "search", G_CALLBACK (modest_msg_view_window_find_toolbar_search), obj);
803         priv->last_search = NULL;
804
805         modest_msg_view_window_show_toolbar (MODEST_WINDOW (obj), TRUE);
806
807         /* Init the clipboard actions dim status */
808         modest_msg_view_grab_focus(MODEST_MSG_VIEW (priv->msg_view));
809
810         update_window_title (MODEST_MSG_VIEW_WINDOW (obj));
811
812
813 }
814
815 /* FIXME: parameter checks */
816 ModestWindow *
817 modest_msg_view_window_new_with_header_model (TnyMsg *msg, 
818                                               const gchar *modest_account_name,
819                                               const gchar *msg_uid,
820                                               GtkTreeModel *model, 
821                                               GtkTreeRowReference *row_reference)
822 {
823         ModestMsgViewWindow *window = NULL;
824         ModestMsgViewWindowPrivate *priv = NULL;
825         TnyFolder *header_folder = NULL;
826         ModestHeaderView *header_view = NULL;
827         ModestWindow *main_window = NULL;
828         ModestWindowMgr *mgr = NULL;
829
830         MODEST_DEBUG_BLOCK (
831                modest_tny_mime_part_to_string (TNY_MIME_PART (msg), 0);
832         );
833
834         mgr = modest_runtime_get_window_mgr ();
835         window = MODEST_MSG_VIEW_WINDOW (modest_window_mgr_get_msg_view_window (mgr));
836         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window), NULL);
837
838         modest_msg_view_window_construct (window, modest_account_name, msg_uid);
839
840         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
841
842         /* Remember the message list's TreeModel so we can detect changes 
843          * and change the list selection when necessary: */
844
845         main_window = modest_window_mgr_get_main_window(mgr, FALSE); /* don't create */
846         if (main_window) {
847                 header_view = MODEST_HEADER_VIEW(modest_main_window_get_child_widget(
848                                                          MODEST_MAIN_WINDOW(main_window),
849                                                          MODEST_MAIN_WINDOW_WIDGET_TYPE_HEADER_VIEW));
850         }
851         
852         if (header_view != NULL){
853                 header_folder = modest_header_view_get_folder(header_view);
854                 /* This could happen if the header folder was
855                    unseleted before opening this msg window (for
856                    example if the user selects an account in the
857                    folder view of the main window */
858                 if (header_folder) {
859                         priv->is_outbox = (modest_tny_folder_guess_folder_type (header_folder) == TNY_FOLDER_TYPE_OUTBOX);
860                         priv->header_folder_id = tny_folder_get_id(header_folder);
861                         g_assert(priv->header_folder_id != NULL);
862                         g_object_unref(header_folder);
863                 }
864         }
865
866         /* Setup row references and connect signals */
867         priv->header_model = g_object_ref (model);
868
869         if (row_reference) {
870                 priv->row_reference = gtk_tree_row_reference_copy (row_reference);
871                 priv->next_row_reference = gtk_tree_row_reference_copy (row_reference);
872                 select_next_valid_row (model, &(priv->next_row_reference), TRUE, priv->is_outbox);
873         } else {
874                 priv->row_reference = NULL;
875                 priv->next_row_reference = NULL;
876         }
877
878         /* Connect signals */
879         priv->row_changed_handler = 
880                 g_signal_connect (GTK_TREE_MODEL(model), "row-changed",
881                                   G_CALLBACK(modest_msg_view_window_on_row_changed),
882                                   window);
883         priv->row_deleted_handler = 
884                 g_signal_connect (GTK_TREE_MODEL(model), "row-deleted",
885                                   G_CALLBACK(modest_msg_view_window_on_row_deleted),
886                                   window);
887         priv->row_inserted_handler = 
888                 g_signal_connect (GTK_TREE_MODEL(model), "row-inserted",
889                                   G_CALLBACK(modest_msg_view_window_on_row_inserted),
890                                   window);
891         priv->rows_reordered_handler = 
892                 g_signal_connect(GTK_TREE_MODEL(model), "rows-reordered",
893                                  G_CALLBACK(modest_msg_view_window_on_row_reordered),
894                                  window);
895
896         if (header_view != NULL){
897                 modest_header_view_add_observer(header_view,
898                                 MODEST_HEADER_VIEW_OBSERVER(window));
899         }
900
901         tny_msg_view_set_msg (TNY_MSG_VIEW (priv->msg_view), msg);
902         update_window_title (MODEST_MSG_VIEW_WINDOW (window));
903
904         /* gtk_widget_show_all (GTK_WIDGET (window)); */
905         modest_msg_view_window_update_priority (window);
906         /* Check dimming rules */
907         modest_ui_actions_check_toolbar_dimming_rules (MODEST_WINDOW (window));
908         modest_ui_actions_check_menu_dimming_rules (MODEST_WINDOW (window));
909         modest_window_check_dimming_rules_group (MODEST_WINDOW (window), MODEST_DIMMING_RULES_CLIPBOARD);
910
911         return MODEST_WINDOW(window);
912 }
913
914 ModestWindow *
915 modest_msg_view_window_new_from_header_view (ModestHeaderView *header_view, 
916                                               const gchar *modest_account_name,
917                                               const gchar *msg_uid,
918                                               GtkTreeRowReference *row_reference)
919 {
920         ModestMsgViewWindow *window = NULL;
921         ModestMsgViewWindowPrivate *priv = NULL;
922         TnyFolder *header_folder = NULL;
923         ModestWindowMgr *mgr = NULL;
924         GtkTreePath *path;
925         GtkTreeIter iter;
926
927         mgr = modest_runtime_get_window_mgr ();
928         window = MODEST_MSG_VIEW_WINDOW (modest_window_mgr_get_msg_view_window (mgr));
929         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window), NULL);
930
931         modest_msg_view_window_construct (window, modest_account_name, msg_uid);
932
933         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
934
935         /* Remember the message list's TreeModel so we can detect changes 
936          * and change the list selection when necessary: */
937
938         if (header_view != NULL){
939                 header_folder = modest_header_view_get_folder(header_view);
940                 /* This could happen if the header folder was
941                    unseleted before opening this msg window (for
942                    example if the user selects an account in the
943                    folder view of the main window */
944                 if (header_folder) {
945                         priv->is_outbox = (modest_tny_folder_guess_folder_type (header_folder) == TNY_FOLDER_TYPE_OUTBOX);
946                         priv->header_folder_id = tny_folder_get_id(header_folder);
947                         g_assert(priv->header_folder_id != NULL);
948                         g_object_unref(header_folder);
949                 }
950         }
951
952         /* Setup row references and connect signals */
953         priv->header_model = gtk_tree_view_get_model (GTK_TREE_VIEW (header_view));
954         g_object_ref (priv->header_model);
955
956         if (row_reference) {
957                 priv->row_reference = gtk_tree_row_reference_copy (row_reference);
958                 priv->next_row_reference = gtk_tree_row_reference_copy (row_reference);
959                 select_next_valid_row (priv->header_model, &(priv->next_row_reference), TRUE, priv->is_outbox);
960         } else {
961                 priv->row_reference = NULL;
962                 priv->next_row_reference = NULL;
963         }
964
965         /* Connect signals */
966         priv->row_changed_handler = 
967                 g_signal_connect (GTK_TREE_MODEL(priv->header_model), "row-changed",
968                                   G_CALLBACK(modest_msg_view_window_on_row_changed),
969                                   window);
970         priv->row_deleted_handler = 
971                 g_signal_connect (GTK_TREE_MODEL(priv->header_model), "row-deleted",
972                                   G_CALLBACK(modest_msg_view_window_on_row_deleted),
973                                   window);
974         priv->row_inserted_handler = 
975                 g_signal_connect (GTK_TREE_MODEL(priv->header_model), "row-inserted",
976                                   G_CALLBACK(modest_msg_view_window_on_row_inserted),
977                                   window);
978         priv->rows_reordered_handler = 
979                 g_signal_connect(GTK_TREE_MODEL(priv->header_model), "rows-reordered",
980                                  G_CALLBACK(modest_msg_view_window_on_row_reordered),
981                                  window);
982
983         if (header_view != NULL){
984                 modest_header_view_add_observer(header_view,
985                                 MODEST_HEADER_VIEW_OBSERVER(window));
986         }
987
988         tny_msg_view_set_msg (TNY_MSG_VIEW (priv->msg_view), NULL);
989
990         path = gtk_tree_row_reference_get_path (row_reference);
991         if (gtk_tree_model_get_iter (priv->header_model, &iter, path)) {
992                 TnyHeader *header;
993                 gtk_tree_model_get (priv->header_model, &iter, 
994                                     TNY_GTK_HEADER_LIST_MODEL_INSTANCE_COLUMN,
995                                     &header, -1);
996                 message_reader (window, priv, header, row_reference);
997         }
998         gtk_tree_path_free (path);
999
1000         /* Check dimming rules */
1001         modest_ui_actions_check_toolbar_dimming_rules (MODEST_WINDOW (window));
1002         modest_ui_actions_check_menu_dimming_rules (MODEST_WINDOW (window));
1003         modest_window_check_dimming_rules_group (MODEST_WINDOW (window), MODEST_DIMMING_RULES_CLIPBOARD);
1004
1005         return MODEST_WINDOW(window);
1006 }
1007
1008 ModestWindow *
1009 modest_msg_view_window_new_for_search_result (TnyMsg *msg, 
1010                                               const gchar *modest_account_name,
1011                                               const gchar *msg_uid)
1012 {
1013         ModestMsgViewWindow *window = NULL;
1014         ModestMsgViewWindowPrivate *priv = NULL;
1015         ModestWindowMgr *mgr = NULL;
1016
1017         mgr = modest_runtime_get_window_mgr ();
1018         window = MODEST_MSG_VIEW_WINDOW (modest_window_mgr_get_msg_view_window (mgr));
1019         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window), NULL);
1020         modest_msg_view_window_construct (window, modest_account_name, msg_uid);
1021
1022         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
1023
1024         /* Remember that this is a search result, 
1025          * so we can disable some UI appropriately: */
1026         priv->is_search_result = TRUE;
1027
1028         tny_msg_view_set_msg (TNY_MSG_VIEW (priv->msg_view), msg);
1029         
1030         update_window_title (window);
1031         /* gtk_widget_show_all (GTK_WIDGET (window));*/
1032         modest_msg_view_window_update_priority (window);
1033
1034         /* Check dimming rules */
1035         modest_ui_actions_check_toolbar_dimming_rules (MODEST_WINDOW (window));
1036         modest_ui_actions_check_menu_dimming_rules (MODEST_WINDOW (window));
1037         modest_window_check_dimming_rules_group (MODEST_WINDOW (window), MODEST_DIMMING_RULES_CLIPBOARD);
1038
1039         return MODEST_WINDOW(window);
1040 }
1041
1042 ModestWindow *
1043 modest_msg_view_window_new_for_attachment (TnyMsg *msg, 
1044                             const gchar *modest_account_name,
1045                             const gchar *msg_uid)
1046 {
1047         GObject *obj = NULL;
1048         ModestMsgViewWindowPrivate *priv;       
1049         ModestWindowMgr *mgr = NULL;
1050
1051         g_return_val_if_fail (msg, NULL);
1052         mgr = modest_runtime_get_window_mgr ();
1053         obj = G_OBJECT (modest_window_mgr_get_msg_view_window (mgr));
1054         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (obj);
1055         modest_msg_view_window_construct (MODEST_MSG_VIEW_WINDOW (obj), 
1056                 modest_account_name, msg_uid);
1057
1058         tny_msg_view_set_msg (TNY_MSG_VIEW (priv->msg_view), msg);
1059         update_window_title (MODEST_MSG_VIEW_WINDOW (obj));
1060
1061         /* gtk_widget_show_all (GTK_WIDGET (obj)); */
1062
1063         /* Check dimming rules */
1064         modest_ui_actions_check_toolbar_dimming_rules (MODEST_WINDOW (obj));
1065         modest_ui_actions_check_menu_dimming_rules (MODEST_WINDOW (obj));
1066         modest_window_check_dimming_rules_group (MODEST_WINDOW (obj), MODEST_DIMMING_RULES_CLIPBOARD);
1067
1068         return MODEST_WINDOW(obj);
1069 }
1070
1071 static void
1072 modest_msg_view_window_on_row_changed (GtkTreeModel *header_model,
1073                                        GtkTreePath *arg1,
1074                                        GtkTreeIter *arg2,
1075                                        ModestMsgViewWindow *window)
1076 {
1077         check_dimming_rules_after_change (window);
1078 }
1079
1080 static void 
1081 modest_msg_view_window_on_row_deleted(GtkTreeModel *header_model,
1082                                       GtkTreePath *arg1,
1083                                       ModestMsgViewWindow *window)
1084 {
1085         check_dimming_rules_after_change (window);
1086 }
1087         /* The window could have dissapeared */
1088
1089 static void
1090 check_dimming_rules_after_change (ModestMsgViewWindow *window)
1091 {
1092         modest_ui_actions_check_menu_dimming_rules (MODEST_WINDOW (window));
1093         modest_ui_actions_check_toolbar_dimming_rules (MODEST_WINDOW (window));
1094 }
1095
1096
1097 /* On insertions we check if the folder still has the message we are
1098  * showing or do not. If do not, we do nothing. Which means we are still
1099  * not attached to any header folder and thus next/prev buttons are
1100  * still dimmed. Once the message that is shown by msg-view is found, the
1101  * new model of header-view will be attached and the references will be set.
1102  * On each further insertions dimming rules will be checked. However
1103  * this requires extra CPU time at least works.
1104  * (An message might be deleted from TnyFolder and thus will not be
1105  * inserted into the model again for example if it is removed by the
1106  * imap server and the header view is refreshed.)
1107  */
1108 static void 
1109 modest_msg_view_window_on_row_inserted (GtkTreeModel *model,
1110                                         GtkTreePath *tree_path,
1111                                         GtkTreeIter *tree_iter,
1112                                         ModestMsgViewWindow *window)
1113 {
1114         ModestMsgViewWindowPrivate *priv = NULL; 
1115         TnyHeader *header = NULL;
1116
1117         g_return_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window));
1118         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
1119
1120         g_assert (model == priv->header_model);
1121         
1122         /* Check if the newly inserted message is the same we are actually
1123          * showing. IF not, we should remain detached from the header model
1124          * and thus prev and next toolbar buttons should remain dimmed. */
1125         gtk_tree_model_get (model, tree_iter, 
1126                             TNY_GTK_HEADER_LIST_MODEL_INSTANCE_COLUMN, 
1127                             &header, -1);
1128
1129         if (TNY_IS_HEADER (header)) {
1130                 gchar *uid = NULL;
1131
1132                 uid = modest_tny_folder_get_header_unique_id (header);
1133                 if (!g_str_equal(priv->msg_uid, uid)) {
1134                         check_dimming_rules_after_change (window);
1135                         g_free(uid);
1136                         g_object_unref (G_OBJECT(header));
1137                         return;
1138                 }
1139                 g_free(uid);
1140                 g_object_unref(G_OBJECT(header));
1141         }
1142
1143         if (priv->row_reference) {
1144                 gtk_tree_row_reference_free (priv->row_reference); 
1145         }
1146
1147         /* Setup row_reference for the actual msg. */
1148         priv->row_reference = gtk_tree_row_reference_new (priv->header_model, tree_path);
1149         if (priv->row_reference == NULL) {
1150                 g_warning("No reference for msg header item.");
1151                 return;
1152         }
1153
1154         /* Now set up next_row_reference. */
1155         if (priv->next_row_reference) {
1156                 gtk_tree_row_reference_free (priv->next_row_reference); 
1157         }
1158
1159         priv->next_row_reference = gtk_tree_row_reference_copy (priv->row_reference);
1160         select_next_valid_row (priv->header_model,
1161                                &(priv->next_row_reference), FALSE, priv->is_outbox);
1162
1163         /* Connect the remaining callbacks to become able to detect
1164          * changes in header-view. */
1165         priv->row_changed_handler = 
1166                 g_signal_connect (priv->header_model, "row-changed",
1167                                   G_CALLBACK (modest_msg_view_window_on_row_changed),
1168                                   window);
1169         priv->row_deleted_handler = 
1170                 g_signal_connect (priv->header_model, "row-deleted",
1171                                   G_CALLBACK (modest_msg_view_window_on_row_deleted),
1172                                   window);
1173         priv->rows_reordered_handler = 
1174                 g_signal_connect (priv->header_model, "rows-reordered",
1175                                   G_CALLBACK (modest_msg_view_window_on_row_reordered),
1176                                   window);
1177
1178         check_dimming_rules_after_change (window);      
1179 }
1180
1181 static void 
1182 modest_msg_view_window_on_row_reordered (GtkTreeModel *header_model,
1183                                          GtkTreePath *arg1,
1184                                          GtkTreeIter *arg2,
1185                                          gpointer arg3,
1186                                          ModestMsgViewWindow *window)
1187 {
1188         ModestMsgViewWindowPrivate *priv = NULL; 
1189         gboolean already_changed = FALSE;
1190
1191         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE(window);
1192
1193         /* If the current row was reordered select the proper next
1194            valid row. The same if the next row reference changes */
1195         if (priv->row_reference && 
1196             gtk_tree_row_reference_valid (priv->row_reference)) {
1197                 GtkTreePath *path;
1198                 path = gtk_tree_row_reference_get_path (priv->row_reference);
1199                 if (gtk_tree_path_compare (path, arg1) == 0) {
1200                         if (priv->next_row_reference) {
1201                                 gtk_tree_row_reference_free (priv->next_row_reference);
1202                         }
1203                         priv->next_row_reference = gtk_tree_row_reference_copy (priv->row_reference);
1204                         select_next_valid_row (header_model, &(priv->next_row_reference), FALSE, priv->is_outbox);
1205                         already_changed = TRUE;
1206                 }
1207                 gtk_tree_path_free (path);
1208         }
1209         if (!already_changed &&
1210             priv->next_row_reference &&
1211             gtk_tree_row_reference_valid (priv->next_row_reference)) {
1212                 GtkTreePath *path;
1213                 path = gtk_tree_row_reference_get_path (priv->next_row_reference);
1214                 if (gtk_tree_path_compare (path, arg1) == 0) {
1215                         if (priv->next_row_reference) {
1216                                 gtk_tree_row_reference_free (priv->next_row_reference);
1217                         }
1218                         priv->next_row_reference = gtk_tree_row_reference_copy (priv->row_reference);
1219                         select_next_valid_row (header_model, &(priv->next_row_reference), FALSE, priv->is_outbox);
1220                 }
1221                 gtk_tree_path_free (path);
1222         }
1223         check_dimming_rules_after_change (window);
1224 }
1225
1226 /* The modest_msg_view_window_update_model_replaced implements update
1227  * function for ModestHeaderViewObserver. Checks whether the TnyFolder
1228  * actually belongs to the header-view is the same as the TnyFolder of
1229  * the message of msg-view or not. If they are different, there is
1230  * nothing to do. If they are the same, then the model has replaced and
1231  * the reference in msg-view shall be replaced from the old model to
1232  * the new model. In this case the view will be detached from it's
1233  * header folder. From this point the next/prev buttons are dimmed.
1234  */
1235 static void 
1236 modest_msg_view_window_update_model_replaced (ModestHeaderViewObserver *observer,
1237                                               GtkTreeModel *model,
1238                                               const gchar *tny_folder_id)
1239 {
1240         ModestMsgViewWindowPrivate *priv = NULL; 
1241         ModestMsgViewWindow *window = NULL;
1242
1243         g_assert(MODEST_IS_HEADER_VIEW_OBSERVER(observer));
1244         g_assert(MODEST_IS_MSG_VIEW_WINDOW(observer));
1245
1246         window = MODEST_MSG_VIEW_WINDOW(observer);
1247         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE(window);
1248
1249         /* If there is an other folder in the header-view then we do
1250          * not care about it's model (msg list). Else if the
1251          * header-view shows the folder the msg shown by us is in, we
1252          * shall replace our model reference and make some check. */
1253         if(model == NULL || tny_folder_id == NULL || 
1254            (priv->header_folder_id && !g_str_equal(tny_folder_id, priv->header_folder_id)))
1255                 return;
1256
1257         /* Model is changed(replaced), so we should forget the old
1258          * one. Because there might be other references and there
1259          * might be some change on the model even if we unreferenced
1260          * it, we need to disconnect our signals here. */
1261         if (priv->header_model) {
1262                 if (g_signal_handler_is_connected(G_OBJECT (priv->header_model), 
1263                                                   priv->row_changed_handler))
1264                         g_signal_handler_disconnect(G_OBJECT (priv->header_model), 
1265                                                     priv->row_changed_handler);
1266                 if (g_signal_handler_is_connected(G_OBJECT (priv->header_model), 
1267                                                   priv->row_deleted_handler))
1268                         g_signal_handler_disconnect(G_OBJECT (priv->header_model), 
1269                                                     priv->row_deleted_handler);
1270                 if (g_signal_handler_is_connected(G_OBJECT (priv->header_model), 
1271                                                   priv->row_inserted_handler))
1272                         g_signal_handler_disconnect(G_OBJECT (priv->header_model), 
1273                                                     priv->row_inserted_handler);
1274                 if (g_signal_handler_is_connected(G_OBJECT (priv->header_model), 
1275                                                   priv->rows_reordered_handler))
1276                         g_signal_handler_disconnect(G_OBJECT (priv->header_model), 
1277                                                     priv->rows_reordered_handler);
1278
1279                 /* Frees */
1280                 if (priv->row_reference)
1281                         gtk_tree_row_reference_free (priv->row_reference);
1282                 if (priv->next_row_reference)
1283                         gtk_tree_row_reference_free (priv->next_row_reference);
1284                 g_object_unref(priv->header_model);
1285
1286                 /* Initialize */
1287                 priv->row_changed_handler = 0;
1288                 priv->row_deleted_handler = 0;
1289                 priv->row_inserted_handler = 0;
1290                 priv->rows_reordered_handler = 0;
1291                 priv->next_row_reference = NULL;
1292                 priv->row_reference = NULL;
1293                 priv->header_model = NULL;
1294         }
1295
1296         priv->header_model = g_object_ref (model);
1297
1298         /* Also we must connect to the new model for row insertions.
1299          * Only for insertions now. We will need other ones only after
1300          * the msg is show by msg-view is added to the new model. */
1301         priv->row_inserted_handler =
1302                 g_signal_connect (priv->header_model, "row-inserted",
1303                                   G_CALLBACK(modest_msg_view_window_on_row_inserted),
1304                                   window);
1305
1306         modest_ui_actions_check_menu_dimming_rules(MODEST_WINDOW(window));
1307         modest_ui_actions_check_toolbar_dimming_rules(MODEST_WINDOW(window));
1308 }
1309
1310 gboolean 
1311 modest_msg_view_window_toolbar_on_transfer_mode     (ModestMsgViewWindow *self)
1312 {
1313         ModestMsgViewWindowPrivate *priv= NULL; 
1314
1315         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (self), FALSE);
1316         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (self);
1317
1318         return priv->progress_hint;
1319 }
1320
1321 TnyHeader*
1322 modest_msg_view_window_get_header (ModestMsgViewWindow *self)
1323 {
1324         ModestMsgViewWindowPrivate *priv= NULL; 
1325         TnyMsg *msg = NULL;
1326         TnyHeader *header = NULL;
1327         GtkTreePath *path = NULL;
1328         GtkTreeIter iter;
1329
1330         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (self), NULL);
1331         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (self);
1332
1333         /* If the message was not obtained from a treemodel,
1334          * for instance if it was opened directly by the search UI:
1335          */
1336         if (priv->header_model == NULL || 
1337             priv->row_reference == NULL ||
1338             !gtk_tree_row_reference_valid (priv->row_reference)) {
1339                 msg = modest_msg_view_window_get_message (self);
1340                 if (msg) {
1341                         header = tny_msg_get_header (msg);
1342                         g_object_unref (msg);
1343                 }
1344                 return header;
1345         }
1346
1347         /* Get iter of the currently selected message in the header view: */
1348         path = gtk_tree_row_reference_get_path (priv->row_reference);
1349         g_return_val_if_fail (path != NULL, NULL);
1350         gtk_tree_model_get_iter (priv->header_model, 
1351                                  &iter, 
1352                                  path);
1353
1354         /* Get current message header */
1355         gtk_tree_model_get (priv->header_model, &iter, 
1356                             TNY_GTK_HEADER_LIST_MODEL_INSTANCE_COLUMN, 
1357                             &header, -1);
1358
1359         gtk_tree_path_free (path);
1360         return header;
1361 }
1362
1363 TnyMsg*
1364 modest_msg_view_window_get_message (ModestMsgViewWindow *self)
1365 {
1366         ModestMsgViewWindowPrivate *priv;
1367         
1368         g_return_val_if_fail (self, NULL);
1369         
1370         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE(self);
1371         
1372         return tny_msg_view_get_msg (TNY_MSG_VIEW (priv->msg_view));
1373 }
1374
1375 const gchar*
1376 modest_msg_view_window_get_message_uid (ModestMsgViewWindow *self)
1377 {
1378         ModestMsgViewWindowPrivate *priv;
1379
1380         g_return_val_if_fail (self, NULL);
1381         
1382         priv  = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (self);
1383
1384         return (const gchar*) priv->msg_uid;
1385 }
1386
1387 static void 
1388 modest_msg_view_window_toggle_find_toolbar (GtkToggleAction *toggle,
1389                                             gpointer data)
1390 {
1391         ModestMsgViewWindow *window = MODEST_MSG_VIEW_WINDOW (data);
1392         ModestMsgViewWindowPrivate *priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
1393         ModestWindowPrivate *parent_priv = MODEST_WINDOW_GET_PRIVATE (window);
1394         gboolean is_active;
1395         GtkAction *action;
1396
1397         is_active = gtk_toggle_action_get_active (toggle);
1398
1399         if (is_active) {
1400                 gtk_widget_show (priv->find_toolbar);
1401                 hildon_find_toolbar_highlight_entry (HILDON_FIND_TOOLBAR (priv->find_toolbar), TRUE);
1402         } else {
1403                 gtk_widget_hide (priv->find_toolbar);
1404                 modest_msg_view_grab_focus (MODEST_MSG_VIEW (priv->msg_view));
1405         }
1406
1407         /* update the toggle buttons status */
1408         action = gtk_ui_manager_get_action (parent_priv->ui_manager, "/ToolBar/FindInMessage");
1409         if (action)
1410                 modest_utils_toggle_action_set_active_block_notify (GTK_TOGGLE_ACTION (action), is_active);
1411
1412 }
1413
1414 static void
1415 modest_msg_view_window_find_toolbar_close (GtkWidget *widget,
1416                                            ModestMsgViewWindow *obj)
1417 {
1418         GtkToggleAction *toggle;
1419         ModestWindowPrivate *parent_priv;
1420         ModestMsgViewWindowPrivate *priv;
1421
1422         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (obj);
1423         parent_priv = MODEST_WINDOW_GET_PRIVATE (obj);
1424
1425         toggle = GTK_TOGGLE_ACTION (gtk_ui_manager_get_action (parent_priv->ui_manager, "/ToolBar/FindInMessage"));
1426         gtk_toggle_action_set_active (toggle, FALSE);
1427         modest_msg_view_grab_focus (MODEST_MSG_VIEW (priv->msg_view));
1428 }
1429
1430 static void
1431 modest_msg_view_window_find_toolbar_search (GtkWidget *widget,
1432                                            ModestMsgViewWindow *obj)
1433 {
1434         gchar *current_search;
1435         ModestMsgViewWindowPrivate *priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (obj);
1436
1437         if (modest_mime_part_view_is_empty (MODEST_MIME_PART_VIEW (priv->msg_view))) {
1438                 hildon_banner_show_information (NULL, NULL, _("mail_ib_nothing_to_find"));
1439                 return;
1440         }
1441
1442         g_object_get (G_OBJECT (widget), "prefix", &current_search, NULL);
1443
1444         if ((current_search == NULL) || (strcmp (current_search, "") == 0)) {
1445                 g_free (current_search);
1446                 hildon_banner_show_information (NULL, NULL, dgettext("hildon-common-strings", "ecdg_ib_find_rep_enter_text"));
1447                 return;
1448         }
1449
1450         if ((priv->last_search == NULL) || (strcmp (priv->last_search, current_search) != 0)) {
1451                 gboolean result;
1452                 g_free (priv->last_search);
1453                 priv->last_search = g_strdup (current_search);
1454                 result = modest_isearch_view_search (MODEST_ISEARCH_VIEW (priv->msg_view),
1455                                                      priv->last_search);
1456                 if (!result) {
1457                         hildon_banner_show_information (NULL, NULL, dgettext("hildon-libs", "ckct_ib_find_no_matches"));
1458                         g_free (priv->last_search);
1459                         priv->last_search = NULL;
1460                 } else {
1461                         modest_msg_view_grab_focus (MODEST_MSG_VIEW (priv->msg_view));
1462                         hildon_find_toolbar_highlight_entry (HILDON_FIND_TOOLBAR (priv->find_toolbar), TRUE);
1463                 }
1464         } else {
1465                 if (!modest_isearch_view_search_next (MODEST_ISEARCH_VIEW (priv->msg_view))) {
1466                         hildon_banner_show_information (NULL, NULL, dgettext("hildon-libs", "ckct_ib_find_search_complete"));
1467                         g_free (priv->last_search);
1468                         priv->last_search = NULL;
1469                 } else {
1470                         modest_msg_view_grab_focus (MODEST_MSG_VIEW (priv->msg_view));
1471                         hildon_find_toolbar_highlight_entry (HILDON_FIND_TOOLBAR (priv->find_toolbar), TRUE);
1472                 }
1473         }
1474         
1475         g_free (current_search);
1476                 
1477 }
1478
1479 static void
1480 modest_msg_view_window_set_zoom (ModestWindow *window,
1481                                  gdouble zoom)
1482 {
1483         ModestMsgViewWindowPrivate *priv;
1484         ModestWindowPrivate *parent_priv;
1485      
1486         g_return_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window));
1487
1488         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
1489         parent_priv = MODEST_WINDOW_GET_PRIVATE (window);
1490         modest_zoomable_set_zoom (MODEST_ZOOMABLE (priv->msg_view), zoom);
1491
1492 }
1493
1494 static gdouble
1495 modest_msg_view_window_get_zoom (ModestWindow *window)
1496 {
1497         ModestMsgViewWindowPrivate *priv;
1498      
1499         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window), 1.0);
1500
1501         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
1502         return modest_zoomable_get_zoom (MODEST_ZOOMABLE (priv->msg_view));
1503 }
1504
1505 static gboolean
1506 modest_msg_view_window_zoom_plus (ModestWindow *window)
1507 {
1508         gdouble zoom_level;
1509         ModestMsgViewWindowPrivate *priv;
1510      
1511         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window), 1.0);
1512         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
1513   
1514         zoom_level =  modest_zoomable_get_zoom (MODEST_ZOOMABLE (priv->msg_view));
1515
1516         if (zoom_level >= 2.0) {
1517                 hildon_banner_show_information (NULL, NULL, dgettext("hildon-common-strings", "ckct_ib_max_zoom_level_reached"));
1518                 return FALSE;
1519         } else if (zoom_level >= 1.5) {
1520                 zoom_level = 2.0;
1521         } else if (zoom_level >= 1.2) {
1522                 zoom_level = 1.5;
1523         } else if (zoom_level >= 1.0) {
1524                 zoom_level = 1.2;
1525         } else if (zoom_level >= 0.8) {
1526                 zoom_level = 1.0;
1527         } else if (zoom_level >= 0.5) {
1528                 zoom_level = 0.8;
1529         } else {
1530                 zoom_level = 0.5;
1531         }
1532
1533         /* set zoom level */
1534         modest_zoomable_set_zoom (MODEST_ZOOMABLE (priv->msg_view), zoom_level);
1535
1536         return TRUE;
1537         
1538 }
1539
1540 static gboolean
1541 modest_msg_view_window_zoom_minus (ModestWindow *window)
1542 {
1543         gdouble zoom_level;
1544         ModestMsgViewWindowPrivate *priv;
1545      
1546         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window), 1.0);
1547         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
1548   
1549         zoom_level =  modest_zoomable_get_zoom (MODEST_ZOOMABLE (priv->msg_view));
1550
1551         if (zoom_level <= 0.5) {
1552                           hildon_banner_show_information (NULL, NULL, dgettext("hildon-common-strings", "ckct_ib_min_zoom_level_reached"));
1553                 return FALSE;
1554         } else if (zoom_level <= 0.8) {
1555                 zoom_level = 0.5;
1556         } else if (zoom_level <= 1.0) {
1557                 zoom_level = 0.8;
1558         } else if (zoom_level <= 1.2) {
1559                 zoom_level = 1.0;
1560         } else if (zoom_level <= 1.5) {
1561                 zoom_level = 1.2;
1562         } else if (zoom_level <= 2.0) {
1563                 zoom_level = 1.5;
1564         } else {
1565                 zoom_level = 2.0;
1566         }
1567
1568         /* set zoom level */
1569         modest_zoomable_set_zoom (MODEST_ZOOMABLE (priv->msg_view), zoom_level);
1570
1571         return TRUE;
1572         
1573 }
1574
1575 static gboolean
1576 modest_msg_view_window_key_event (GtkWidget *window,
1577                                   GdkEventKey *event,
1578                                   gpointer userdata)
1579 {
1580         GtkWidget *focus;
1581
1582         focus = gtk_window_get_focus (GTK_WINDOW (window));
1583
1584         /* for the find toolbar case */
1585         if (focus && GTK_IS_ENTRY (focus)) {
1586                 if (event->keyval == GDK_BackSpace) {
1587                         GdkEvent *copy;
1588                         copy = gdk_event_copy ((GdkEvent *) event);
1589                         gtk_widget_event (focus, copy);
1590                         gdk_event_free (copy);
1591                         return TRUE;
1592                 } else 
1593                         return FALSE;
1594         }
1595         if (event->keyval == GDK_Up || event->keyval == GDK_KP_Up ||
1596             event->keyval == GDK_Down || event->keyval == GDK_KP_Down ||
1597             event->keyval == GDK_Page_Up || event->keyval == GDK_KP_Page_Up ||
1598             event->keyval == GDK_Page_Down || event->keyval == GDK_KP_Page_Down ||
1599             event->keyval == GDK_Home || event->keyval == GDK_KP_Home ||
1600             event->keyval == GDK_End || event->keyval == GDK_KP_End) {
1601                 /* ModestMsgViewWindowPrivate *priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window); */
1602                 /* gboolean return_value; */
1603
1604                 if (event->type == GDK_KEY_PRESS) {
1605                         GtkScrollType scroll_type;
1606                         
1607                         switch (event->keyval) {
1608                         case GDK_Up: 
1609                         case GDK_KP_Up:
1610                                 scroll_type = GTK_SCROLL_STEP_UP; break;
1611                         case GDK_Down: 
1612                         case GDK_KP_Down:
1613                                 scroll_type = GTK_SCROLL_STEP_DOWN; break;
1614                         case GDK_Page_Up:
1615                         case GDK_KP_Page_Up:
1616                                 scroll_type = GTK_SCROLL_PAGE_UP; break;
1617                         case GDK_Page_Down:
1618                         case GDK_KP_Page_Down:
1619                                 scroll_type = GTK_SCROLL_PAGE_DOWN; break;
1620                         case GDK_Home:
1621                         case GDK_KP_Home:
1622                                 scroll_type = GTK_SCROLL_START; break;
1623                         case GDK_End:
1624                         case GDK_KP_End:
1625                                 scroll_type = GTK_SCROLL_END; break;
1626                         default: scroll_type = GTK_SCROLL_NONE;
1627                         }
1628                         
1629                         /* g_signal_emit_by_name (G_OBJECT (priv->main_scroll), "scroll-child",  */
1630                         /*                     scroll_type, FALSE, &return_value); */
1631                         return FALSE;
1632                 } else {
1633                         return FALSE;
1634                 }
1635         } else {
1636                 return FALSE;
1637         }
1638 }
1639
1640 gboolean
1641 modest_msg_view_window_last_message_selected (ModestMsgViewWindow *window)
1642 {
1643         GtkTreePath *path;
1644         ModestMsgViewWindowPrivate *priv;
1645         GtkTreeIter tmp_iter;
1646         gboolean is_last_selected;
1647
1648         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window), TRUE);
1649         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
1650
1651         /*if no model (so no rows at all), then virtually we are the last*/
1652         if (!priv->header_model || !priv->row_reference)
1653                 return TRUE;
1654
1655         if (!gtk_tree_row_reference_valid (priv->row_reference))
1656                 return TRUE;
1657
1658         path = gtk_tree_row_reference_get_path (priv->row_reference);
1659         if (path == NULL)
1660                 return TRUE;
1661
1662         is_last_selected = TRUE;
1663         while (is_last_selected) {
1664                 TnyHeader *header;
1665                 gtk_tree_path_next (path);
1666                 if (!gtk_tree_model_get_iter (priv->header_model, &tmp_iter, path))
1667                         break;
1668                 gtk_tree_model_get (priv->header_model, &tmp_iter,
1669                                 TNY_GTK_HEADER_LIST_MODEL_INSTANCE_COLUMN,
1670                                 &header, -1);
1671                 if (header) {
1672                         if (msg_is_visible (header, priv->is_outbox))
1673                                 is_last_selected = FALSE;
1674                         g_object_unref(G_OBJECT(header));
1675                 }
1676         }
1677         gtk_tree_path_free (path);
1678         return is_last_selected;
1679 }
1680
1681 gboolean
1682 modest_msg_view_window_has_headers_model (ModestMsgViewWindow *window)
1683 {
1684         ModestMsgViewWindowPrivate *priv;
1685
1686         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window), TRUE);
1687         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
1688
1689         return priv->header_model != NULL;
1690 }
1691
1692 gboolean
1693 modest_msg_view_window_is_search_result (ModestMsgViewWindow *window)
1694 {
1695         ModestMsgViewWindowPrivate *priv;
1696
1697         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window), TRUE);
1698         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
1699
1700         return priv->is_search_result;
1701 }
1702
1703 static gboolean
1704 msg_is_visible (TnyHeader *header, gboolean check_outbox)
1705 {
1706         if ((tny_header_get_flags(header) & TNY_HEADER_FLAG_DELETED))
1707                 return FALSE;
1708         if (!check_outbox) {
1709                 return TRUE;
1710         } else {
1711                 ModestTnySendQueueStatus status;
1712                 status = modest_tny_all_send_queues_get_msg_status (header);
1713                 return ((status != MODEST_TNY_SEND_QUEUE_FAILED) &&
1714                         (status != MODEST_TNY_SEND_QUEUE_SENDING));
1715         }
1716 }
1717
1718 gboolean
1719 modest_msg_view_window_first_message_selected (ModestMsgViewWindow *window)
1720 {
1721         GtkTreePath *path;
1722         ModestMsgViewWindowPrivate *priv;
1723         gboolean is_first_selected;
1724         GtkTreeIter tmp_iter;
1725
1726         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window), TRUE);
1727         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
1728
1729         /*if no model (so no rows at all), then virtually we are the first*/
1730         if (!priv->header_model || !priv->row_reference)
1731                 return TRUE;
1732
1733         if (!gtk_tree_row_reference_valid (priv->row_reference))
1734                 return TRUE;
1735
1736         path = gtk_tree_row_reference_get_path (priv->row_reference);
1737         if (!path)
1738                 return TRUE;
1739
1740         is_first_selected = TRUE;
1741         while (is_first_selected) {
1742                 TnyHeader *header;
1743                 if(!gtk_tree_path_prev (path))
1744                         break;
1745                 /* Here the 'if' is needless for logic, but let make sure
1746                  * iter is valid for gtk_tree_model_get. */
1747                 if (!gtk_tree_model_get_iter (priv->header_model, &tmp_iter, path))
1748                         break;
1749                 gtk_tree_model_get (priv->header_model, &tmp_iter,
1750                                 TNY_GTK_HEADER_LIST_MODEL_INSTANCE_COLUMN,
1751                                 &header, -1);
1752                 if (header) {
1753                         if (msg_is_visible (header, priv->is_outbox))
1754                                 is_first_selected = FALSE;
1755                         g_object_unref(G_OBJECT(header));
1756                 }
1757         }
1758         gtk_tree_path_free (path);
1759         return is_first_selected;
1760 }
1761
1762 typedef struct {
1763         TnyHeader *header;
1764         GtkTreeRowReference *row_reference;
1765 } MsgReaderInfo;
1766
1767 static void
1768 message_reader_performer (gboolean canceled, 
1769                           GError *err,
1770                           GtkWindow *parent_window, 
1771                           TnyAccount *account, 
1772                           gpointer user_data)
1773 {
1774         ModestMailOperation *mail_op = NULL;
1775         MsgReaderInfo *info;
1776
1777         info = (MsgReaderInfo *) user_data;
1778         if (canceled || err) {
1779                 goto frees;
1780         }
1781
1782         /* Register the header - it'll be unregistered in the callback */
1783         modest_window_mgr_register_header (modest_runtime_get_window_mgr (), info->header, NULL);
1784
1785         /* New mail operation */
1786         mail_op = modest_mail_operation_new_with_error_handling (G_OBJECT(parent_window),
1787                                                                  modest_ui_actions_disk_operations_error_handler, 
1788                                                                  NULL, NULL);
1789                                 
1790         modest_mail_operation_queue_add (modest_runtime_get_mail_operation_queue (), mail_op);
1791         modest_mail_operation_get_msg (mail_op, info->header, TRUE, view_msg_cb, info->row_reference);
1792         g_object_unref (mail_op);
1793
1794         /* Update dimming rules */
1795         modest_ui_actions_check_toolbar_dimming_rules (MODEST_WINDOW (parent_window));
1796         modest_ui_actions_check_menu_dimming_rules (MODEST_WINDOW (parent_window));
1797
1798  frees:
1799         /* Frees. The row_reference will be freed by the view_msg_cb callback */
1800         g_object_unref (info->header);
1801         g_slice_free (MsgReaderInfo, info);
1802 }
1803
1804
1805 /**
1806  * Reads the message whose summary item is @header. It takes care of
1807  * several things, among others:
1808  *
1809  * If the message was not previously downloaded then ask the user
1810  * before downloading. If there is no connection launch the connection
1811  * dialog. Update toolbar dimming rules.
1812  *
1813  * Returns: TRUE if the mail operation was started, otherwise if the
1814  * user do not want to download the message, or if the user do not
1815  * want to connect, then the operation is not issued
1816  **/
1817 static gboolean
1818 message_reader (ModestMsgViewWindow *window,
1819                 ModestMsgViewWindowPrivate *priv,
1820                 TnyHeader *header,
1821                 GtkTreeRowReference *row_reference)
1822 {
1823         ModestWindowMgr *mgr;
1824         TnyAccount *account;
1825         TnyFolder *folder;
1826         MsgReaderInfo *info;
1827
1828         g_return_val_if_fail (row_reference != NULL, FALSE);
1829
1830         mgr = modest_runtime_get_window_mgr ();
1831         /* Msg download completed */
1832         if (!(tny_header_get_flags (header) & TNY_HEADER_FLAG_CACHED)) {
1833                 /* Ask the user if he wants to download the message if
1834                    we're not online */
1835                 if (!tny_device_is_online (modest_runtime_get_device())) {
1836                         GtkResponseType response;
1837
1838                         response = modest_platform_run_confirmation_dialog (GTK_WINDOW (window),
1839                                                                             _("mcen_nc_get_msg"));
1840                         if (response == GTK_RESPONSE_CANCEL)
1841                                 return FALSE;
1842                 
1843                         folder = tny_header_get_folder (header);
1844                         info = g_slice_new (MsgReaderInfo);
1845                         info->header = g_object_ref (header);
1846                         info->row_reference = gtk_tree_row_reference_copy (row_reference);
1847
1848                         /* Offer the connection dialog if necessary */
1849                         modest_platform_connect_if_remote_and_perform ((GtkWindow *) window, 
1850                                                                        TRUE,
1851                                                                        TNY_FOLDER_STORE (folder),
1852                                                                        message_reader_performer, 
1853                                                                        info);
1854                         g_object_unref (folder);
1855                         return TRUE;
1856                 }
1857         }
1858         
1859         folder = tny_header_get_folder (header);
1860         account = tny_folder_get_account (folder);
1861         info = g_slice_new (MsgReaderInfo);
1862         info->header = g_object_ref (header);
1863         info->row_reference = gtk_tree_row_reference_copy (row_reference);
1864         
1865         message_reader_performer (FALSE, NULL, (GtkWindow *) window, account, info);
1866         g_object_unref (account);
1867         g_object_unref (folder);
1868
1869         return TRUE;
1870 }
1871
1872 gboolean        
1873 modest_msg_view_window_select_next_message (ModestMsgViewWindow *window)
1874 {
1875         ModestMsgViewWindowPrivate *priv;
1876         GtkTreePath *path= NULL;
1877         GtkTreeIter tmp_iter;
1878         TnyHeader *header;
1879         gboolean retval = TRUE;
1880         GtkTreeRowReference *row_reference = NULL;
1881
1882         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window), FALSE);
1883         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
1884
1885         if (!priv->row_reference)
1886                 return FALSE;
1887
1888         /* Update the next row reference if it's not valid. This could
1889            happen if for example the header which it was pointing to,
1890            was deleted. The best place to do it is in the row-deleted
1891            handler but the tinymail model do not work like the glib
1892            tree models and reports the deletion when the row is still
1893            there */
1894         if (!gtk_tree_row_reference_valid (priv->next_row_reference)) {
1895                 if (gtk_tree_row_reference_valid (priv->row_reference)) {
1896                         priv->next_row_reference = gtk_tree_row_reference_copy (priv->row_reference);
1897                         select_next_valid_row (priv->header_model, &(priv->next_row_reference), FALSE, priv->is_outbox);
1898                 }
1899         }
1900         if (priv->next_row_reference)
1901                 path = gtk_tree_row_reference_get_path (priv->next_row_reference);
1902         if (path == NULL)
1903                 return FALSE;
1904
1905         row_reference = gtk_tree_row_reference_copy (priv->next_row_reference);
1906
1907         gtk_tree_model_get_iter (priv->header_model,
1908                                  &tmp_iter,
1909                                  path);
1910         gtk_tree_path_free (path);
1911
1912         gtk_tree_model_get (priv->header_model, &tmp_iter, 
1913                             TNY_GTK_HEADER_LIST_MODEL_INSTANCE_COLUMN,
1914                             &header, -1);
1915         
1916         /* Read the message & show it */
1917         if (!message_reader (window, priv, header, row_reference)) {
1918                 retval = FALSE;
1919         }
1920         gtk_tree_row_reference_free (row_reference);
1921
1922         /* Free */
1923         g_object_unref (header);
1924
1925         return retval;
1926 }
1927
1928 gboolean        
1929 modest_msg_view_window_select_previous_message (ModestMsgViewWindow *window)
1930 {
1931         ModestMsgViewWindowPrivate *priv = NULL;
1932         GtkTreePath *path;
1933         gboolean finished = FALSE;
1934         gboolean retval = FALSE;
1935
1936         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window), FALSE);
1937         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
1938
1939         /* Return inmediatly if there is no header model */
1940         if (!priv->header_model || !priv->row_reference)
1941                 return FALSE;
1942
1943         path = gtk_tree_row_reference_get_path (priv->row_reference);
1944         while (!finished && gtk_tree_path_prev (path)) {
1945                 TnyHeader *header;
1946                 GtkTreeIter iter;
1947
1948                 gtk_tree_model_get_iter (priv->header_model, &iter, path);
1949                 gtk_tree_model_get (priv->header_model, &iter, 
1950                                     TNY_GTK_HEADER_LIST_MODEL_INSTANCE_COLUMN,
1951                                     &header, -1);
1952                 finished = TRUE;
1953                 if (header) {
1954                         if (msg_is_visible (header, priv->is_outbox)) {
1955                                 GtkTreeRowReference *row_reference;
1956                                 row_reference = gtk_tree_row_reference_new (priv->header_model, path);
1957                                 /* Read the message & show it */
1958                                 retval = message_reader (window, priv, header, row_reference);
1959                                 gtk_tree_row_reference_free (row_reference);
1960                         } else {
1961                                 finished = FALSE;
1962                         }
1963                         g_object_unref (header);
1964                 }
1965         }
1966
1967         gtk_tree_path_free (path);
1968         return retval;
1969 }
1970
1971 static void
1972 view_msg_cb (ModestMailOperation *mail_op, 
1973              TnyHeader *header, 
1974              gboolean canceled,
1975              TnyMsg *msg, 
1976              GError *error,
1977              gpointer user_data)
1978 {
1979         ModestMsgViewWindow *self = NULL;
1980         ModestMsgViewWindowPrivate *priv = NULL;
1981         GtkTreeRowReference *row_reference = NULL;
1982
1983         /* Unregister the header (it was registered before creating the mail operation) */
1984         modest_window_mgr_unregister_header (modest_runtime_get_window_mgr (), header);
1985
1986         row_reference = (GtkTreeRowReference *) user_data;
1987         if (canceled) {
1988                 gtk_tree_row_reference_free (row_reference);
1989                 return;
1990         }
1991         
1992         /* If there was any error */
1993         if (!modest_ui_actions_msg_retrieval_check (mail_op, header, msg)) {
1994                 gtk_tree_row_reference_free (row_reference);                    
1995                 return;
1996         }
1997
1998         /* Get the window */ 
1999         self = (ModestMsgViewWindow *) modest_mail_operation_get_source (mail_op);
2000         g_return_if_fail (MODEST_IS_MSG_VIEW_WINDOW (self));
2001         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (self);
2002
2003         /* Update the row reference */
2004         if (priv->row_reference != NULL) {
2005                 gtk_tree_row_reference_free (priv->row_reference);
2006                 priv->row_reference = gtk_tree_row_reference_copy (row_reference);
2007                 if (priv->next_row_reference != NULL) {
2008                         gtk_tree_row_reference_free (priv->next_row_reference);
2009                 }
2010                 priv->next_row_reference = gtk_tree_row_reference_copy (priv->row_reference);
2011                 select_next_valid_row (priv->header_model, &(priv->next_row_reference), TRUE, priv->is_outbox);
2012         }
2013
2014         /* Mark header as read */
2015         if (!(tny_header_get_flags (header) & TNY_HEADER_FLAG_SEEN))
2016                 tny_header_set_flag (header, TNY_HEADER_FLAG_SEEN);
2017
2018         /* Set new message */
2019         if (priv->msg_view != NULL && TNY_IS_MSG_VIEW (priv->msg_view)) {
2020                 tny_msg_view_set_msg (TNY_MSG_VIEW (priv->msg_view), msg);
2021                 modest_msg_view_window_update_priority (self);
2022                 update_window_title (MODEST_MSG_VIEW_WINDOW (self));
2023                 modest_msg_view_grab_focus (MODEST_MSG_VIEW (priv->msg_view));
2024         }
2025
2026         /* Set the new message uid of the window  */
2027         if (priv->msg_uid) {
2028                 g_free (priv->msg_uid);
2029                 priv->msg_uid = modest_tny_folder_get_header_unique_id (header);
2030         }
2031
2032         /* Notify the observers */
2033         g_signal_emit (G_OBJECT (self), signals[MSG_CHANGED_SIGNAL], 
2034                        0, priv->header_model, priv->row_reference);
2035
2036         /* Frees */
2037         g_object_unref (self);
2038         gtk_tree_row_reference_free (row_reference);            
2039 }
2040
2041 TnyFolderType
2042 modest_msg_view_window_get_folder_type (ModestMsgViewWindow *window)
2043 {
2044         ModestMsgViewWindowPrivate *priv;
2045         TnyMsg *msg;
2046         TnyFolderType folder_type;
2047
2048         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
2049
2050         folder_type = TNY_FOLDER_TYPE_UNKNOWN;
2051
2052         msg = tny_msg_view_get_msg (TNY_MSG_VIEW (priv->msg_view));
2053         if (msg) {
2054                 TnyFolder *folder;
2055
2056                 folder = tny_msg_get_folder (msg);
2057                 if (folder) {
2058                         folder_type = modest_tny_folder_guess_folder_type (folder);
2059                         g_object_unref (folder);
2060                 }
2061                 g_object_unref (msg);
2062         }
2063
2064         return folder_type;
2065 }
2066
2067
2068 static void
2069 modest_msg_view_window_update_priority (ModestMsgViewWindow *window)
2070 {
2071         ModestMsgViewWindowPrivate *priv;
2072         TnyHeader *header = NULL;
2073         TnyHeaderFlags flags = 0;
2074
2075         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
2076
2077         if (priv->header_model && priv->row_reference) {
2078                 GtkTreeIter iter;
2079                 GtkTreePath *path = NULL;
2080
2081                 path = gtk_tree_row_reference_get_path (priv->row_reference);
2082                 g_return_if_fail (path != NULL);
2083                 gtk_tree_model_get_iter (priv->header_model, 
2084                                          &iter, 
2085                                          gtk_tree_row_reference_get_path (priv->row_reference));
2086
2087                 gtk_tree_model_get (priv->header_model, &iter, TNY_GTK_HEADER_LIST_MODEL_INSTANCE_COLUMN,
2088                                     &header, -1);
2089                 gtk_tree_path_free (path);
2090         } else {
2091                 TnyMsg *msg;
2092                 msg = tny_msg_view_get_msg (TNY_MSG_VIEW (priv->msg_view));
2093                 if (msg) {
2094                         header = tny_msg_get_header (msg);
2095                         g_object_unref (msg);
2096                 }
2097         }
2098
2099         if (header) {
2100                 flags = tny_header_get_flags (header);
2101                 g_object_unref(G_OBJECT(header));
2102         }
2103
2104         modest_msg_view_set_priority (MODEST_MSG_VIEW(priv->msg_view), flags);
2105
2106 }
2107
2108 static void
2109 toolbar_resize (ModestMsgViewWindow *self)
2110 {
2111         ModestMsgViewWindowPrivate *priv = NULL;
2112         ModestWindowPrivate *parent_priv = NULL;
2113         GtkWidget *widget;
2114         gint static_button_size;
2115         ModestWindowMgr *mgr;
2116
2117         g_return_if_fail (MODEST_IS_MSG_VIEW_WINDOW (self));
2118         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (self);
2119         parent_priv = MODEST_WINDOW_GET_PRIVATE(self);
2120
2121         mgr = modest_runtime_get_window_mgr ();
2122         static_button_size = modest_window_mgr_get_fullscreen_mode (mgr)?118:108;
2123
2124         if (parent_priv->toolbar) {
2125                 /* left size buttons */
2126                 widget = gtk_ui_manager_get_widget (parent_priv->ui_manager, "/ToolBar/ToolbarMessageReply");
2127                 gtk_tool_item_set_expand (GTK_TOOL_ITEM (widget), FALSE);
2128                 gtk_tool_item_set_homogeneous (GTK_TOOL_ITEM (widget), FALSE);
2129                 gtk_widget_set_size_request (GTK_WIDGET (widget), static_button_size, -1);
2130                 widget = gtk_ui_manager_get_widget (parent_priv->ui_manager, "/ToolBar/ToolbarMessageMoveTo");
2131                 gtk_tool_item_set_expand (GTK_TOOL_ITEM (widget), FALSE);
2132                 gtk_tool_item_set_homogeneous (GTK_TOOL_ITEM (widget), FALSE);
2133                 gtk_widget_set_size_request (GTK_WIDGET (widget), static_button_size, -1);
2134                 widget = gtk_ui_manager_get_widget (parent_priv->ui_manager, "/ToolBar/ToolbarDeleteMessage");
2135                 gtk_tool_item_set_expand (GTK_TOOL_ITEM (widget), FALSE);
2136                 gtk_tool_item_set_homogeneous (GTK_TOOL_ITEM (widget), FALSE);
2137                 gtk_widget_set_size_request (GTK_WIDGET (widget), static_button_size, -1);
2138                 widget = gtk_ui_manager_get_widget (parent_priv->ui_manager, "/ToolBar/FindInMessage");
2139                 gtk_tool_item_set_expand (GTK_TOOL_ITEM (widget), FALSE);
2140                 gtk_tool_item_set_homogeneous (GTK_TOOL_ITEM (widget), FALSE);
2141                 gtk_widget_set_size_request (GTK_WIDGET (widget), static_button_size, -1);
2142                 
2143                 gtk_tool_item_set_homogeneous (GTK_TOOL_ITEM (priv->next_toolitem), TRUE);
2144                 gtk_tool_item_set_expand (GTK_TOOL_ITEM (priv->next_toolitem), TRUE);
2145                 gtk_tool_item_set_homogeneous (GTK_TOOL_ITEM (priv->prev_toolitem), TRUE);
2146                 gtk_tool_item_set_expand (GTK_TOOL_ITEM (priv->prev_toolitem), TRUE);
2147         }
2148                 
2149 }
2150
2151 static void
2152 modest_msg_view_window_show_toolbar (ModestWindow *self,
2153                                      gboolean show_toolbar)
2154 {
2155         ModestMsgViewWindowPrivate *priv = NULL;
2156         ModestWindowPrivate *parent_priv;
2157         GtkWidget *reply_button = NULL, *menu = NULL;
2158
2159         parent_priv = MODEST_WINDOW_GET_PRIVATE(self);
2160         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE(self);
2161
2162         /* Set optimized view status */
2163         priv->optimized_view = !show_toolbar;
2164
2165         if (!parent_priv->toolbar) {
2166                 parent_priv->toolbar = gtk_ui_manager_get_widget (parent_priv->ui_manager, 
2167                                                                   "/ToolBar");
2168                 gtk_widget_set_no_show_all (parent_priv->toolbar, TRUE);
2169
2170                 priv->next_toolitem = gtk_ui_manager_get_widget (parent_priv->ui_manager, "/ToolBar/ToolbarMessageNext");
2171                 priv->prev_toolitem = gtk_ui_manager_get_widget (parent_priv->ui_manager, "/ToolBar/ToolbarMessageBack");
2172                 toolbar_resize (MODEST_MSG_VIEW_WINDOW (self));
2173
2174                 /* Add to window */
2175                 hildon_window_add_toolbar (HILDON_WINDOW (self), 
2176                                            GTK_TOOLBAR (parent_priv->toolbar));
2177
2178                 /* Set reply button tap and hold menu */
2179                 reply_button = gtk_ui_manager_get_widget (parent_priv->ui_manager, 
2180                                                           "/ToolBar/ToolbarMessageReply");
2181                 menu = gtk_ui_manager_get_widget (parent_priv->ui_manager, 
2182                                                   "/ToolbarReplyCSM");
2183                 if (menu && reply_button)
2184                         gtk_widget_tap_and_hold_setup (GTK_WIDGET (reply_button), menu, NULL, 0);
2185         }
2186
2187         if (show_toolbar) {
2188                 /* Quick hack: this prevents toolbar icons "dance" when progress bar show status is changed */ 
2189                 /* TODO: resize mode migth be GTK_RESIZE_QUEUE, in order to avoid unneccesary shows */
2190                 gtk_container_set_resize_mode (GTK_CONTAINER(parent_priv->toolbar), GTK_RESIZE_IMMEDIATE);
2191
2192                 gtk_widget_show (GTK_WIDGET (parent_priv->toolbar));
2193                 if (modest_msg_view_window_transfer_mode_enabled (MODEST_MSG_VIEW_WINDOW (self))) 
2194                         set_progress_hint (MODEST_MSG_VIEW_WINDOW (self), TRUE);
2195                 else
2196                         set_progress_hint (MODEST_MSG_VIEW_WINDOW (self), FALSE);
2197
2198         } else {
2199                 gtk_widget_set_no_show_all (parent_priv->toolbar, TRUE);
2200                 gtk_widget_hide (GTK_WIDGET (parent_priv->toolbar));
2201         }
2202 }
2203
2204 static void 
2205 modest_msg_view_window_clipboard_owner_change (GtkClipboard *clipboard,
2206                                                GdkEvent *event,
2207                                                ModestMsgViewWindow *window)
2208 {
2209         if (!GTK_WIDGET_VISIBLE (window))
2210                 return;
2211
2212         modest_window_check_dimming_rules_group (MODEST_WINDOW (window), MODEST_DIMMING_RULES_CLIPBOARD);
2213 }
2214
2215 gboolean 
2216 modest_msg_view_window_transfer_mode_enabled (ModestMsgViewWindow *self)
2217 {
2218         ModestMsgViewWindowPrivate *priv;
2219         
2220         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (self), FALSE); 
2221         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE(self);
2222
2223         return priv->progress_hint;
2224 }
2225
2226 static gboolean
2227 observers_empty (ModestMsgViewWindow *self)
2228 {
2229         GSList *tmp = NULL;
2230         ModestMsgViewWindowPrivate *priv;
2231         gboolean is_empty = TRUE;
2232         guint pending_ops = 0;
2233  
2234         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE(self);
2235         tmp = priv->progress_widgets;
2236
2237         /* Check all observers */
2238         while (tmp && is_empty)  {
2239                 pending_ops = modest_progress_object_num_pending_operations (MODEST_PROGRESS_OBJECT(tmp->data));
2240                 is_empty = pending_ops == 0;
2241                 
2242                 tmp = g_slist_next(tmp);
2243         }
2244         
2245         return is_empty;
2246 }
2247
2248 static void
2249 on_account_removed (TnyAccountStore *account_store, 
2250                     TnyAccount *account,
2251                     gpointer user_data)
2252 {
2253         /* Do nothing if it's a transport account, because we only
2254            show the messages of a store account */
2255         if (tny_account_get_account_type(account) == TNY_ACCOUNT_TYPE_STORE) {
2256                 const gchar *parent_acc = NULL;
2257                 const gchar *our_acc = NULL;
2258
2259                 our_acc = modest_window_get_active_account (MODEST_WINDOW (user_data));
2260                 parent_acc = modest_tny_account_get_parent_modest_account_name_for_server_account (account);
2261
2262                 /* Close this window if I'm showing a message of the removed account */
2263                 if (strcmp (parent_acc, our_acc) == 0)
2264                         modest_ui_actions_on_close_window (NULL, MODEST_WINDOW (user_data));
2265         }
2266 }
2267
2268 static void 
2269 on_mail_operation_started (ModestMailOperation *mail_op,
2270                            gpointer user_data)
2271 {
2272         ModestMsgViewWindow *self;
2273         ModestMailOperationTypeOperation op_type;
2274         GSList *tmp;
2275         ModestMsgViewWindowPrivate *priv;
2276         GObject *source = NULL;
2277
2278         self = MODEST_MSG_VIEW_WINDOW (user_data);
2279         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (self);
2280         op_type = modest_mail_operation_get_type_operation (mail_op);
2281         tmp = priv->progress_widgets;
2282         source = modest_mail_operation_get_source(mail_op);
2283         if (G_OBJECT (self) == source) {
2284                 if (op_type == MODEST_MAIL_OPERATION_TYPE_RECEIVE ) {
2285                         set_toolbar_transfer_mode(self);
2286                         while (tmp) {
2287                                 modest_progress_object_add_operation (
2288                                                 MODEST_PROGRESS_OBJECT (tmp->data),
2289                                                 mail_op);
2290                                 tmp = g_slist_next (tmp);
2291                         }
2292                 }
2293         }
2294         g_object_unref (source);
2295 }
2296
2297 static void 
2298 on_mail_operation_finished (ModestMailOperation *mail_op,
2299                             gpointer user_data)
2300 {
2301         ModestMsgViewWindow *self;
2302         ModestMailOperationTypeOperation op_type;
2303         GSList *tmp;
2304         ModestMsgViewWindowPrivate *priv;
2305         
2306         self = MODEST_MSG_VIEW_WINDOW (user_data);
2307         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (self);
2308         op_type = modest_mail_operation_get_type_operation (mail_op);
2309         tmp = priv->progress_widgets;
2310         
2311         if (op_type == MODEST_MAIL_OPERATION_TYPE_RECEIVE ) {
2312                 while (tmp) {
2313                         modest_progress_object_remove_operation (MODEST_PROGRESS_OBJECT (tmp->data),
2314                                                                  mail_op);
2315                         tmp = g_slist_next (tmp);
2316                 }
2317
2318                 /* If no more operations are being observed, NORMAL mode is enabled again */
2319                 if (observers_empty (self)) {
2320                         set_progress_hint (self, FALSE);
2321                 }
2322
2323                 /* Update dimming rules. We have to do this right here
2324                    and not in view_msg_cb because at that point the
2325                    transfer mode is still enabled so the dimming rule
2326                    won't let the user delete the message that has been
2327                    readed for example */
2328                 modest_ui_actions_check_toolbar_dimming_rules (MODEST_WINDOW (self));
2329                 modest_ui_actions_check_menu_dimming_rules (MODEST_WINDOW (self));
2330         }
2331 }
2332
2333 static void
2334 on_queue_changed (ModestMailOperationQueue *queue,
2335                   ModestMailOperation *mail_op,
2336                   ModestMailOperationQueueNotification type,
2337                   ModestMsgViewWindow *self)
2338 {       
2339         ModestMsgViewWindowPrivate *priv;
2340
2341         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (self);
2342
2343         /* If this operations was created by another window, do nothing */
2344         if (!modest_mail_operation_is_mine (mail_op, G_OBJECT(self))) 
2345             return;
2346
2347         if (type == MODEST_MAIL_OPERATION_QUEUE_OPERATION_ADDED) {
2348                 priv->sighandlers = modest_signal_mgr_connect (priv->sighandlers,
2349                                                                G_OBJECT (mail_op),
2350                                                                "operation-started",
2351                                                                G_CALLBACK (on_mail_operation_started),
2352                                                                self);
2353                 priv->sighandlers = modest_signal_mgr_connect (priv->sighandlers,
2354                                                                G_OBJECT (mail_op),
2355                                                                "operation-finished",
2356                                                                G_CALLBACK (on_mail_operation_finished),
2357                                                                self);
2358         } else if (type == MODEST_MAIL_OPERATION_QUEUE_OPERATION_REMOVED) {
2359                 priv->sighandlers = modest_signal_mgr_disconnect (priv->sighandlers,
2360                                                                   G_OBJECT (mail_op),
2361                                                                   "operation-started");
2362                 priv->sighandlers = modest_signal_mgr_disconnect (priv->sighandlers,
2363                                                                   G_OBJECT (mail_op),
2364                                                                   "operation-finished");
2365         }
2366 }
2367
2368 TnyList *
2369 modest_msg_view_window_get_attachments (ModestMsgViewWindow *win) 
2370 {
2371         ModestMsgViewWindowPrivate *priv;
2372         TnyList *selected_attachments = NULL;
2373         
2374         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (win), NULL);
2375         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (win);
2376
2377         selected_attachments = modest_msg_view_get_selected_attachments (MODEST_MSG_VIEW (priv->msg_view));
2378         
2379         return selected_attachments;
2380 }
2381
2382 typedef struct {
2383         gchar *filepath;
2384         GtkWidget *banner;
2385         guint banner_idle_id;
2386 } DecodeAsyncHelper;
2387
2388 static gboolean
2389 decode_async_banner_idle (gpointer user_data)
2390 {
2391         DecodeAsyncHelper *helper = (DecodeAsyncHelper *) user_data;
2392
2393         helper->banner_idle_id = 0;
2394         helper->banner = hildon_banner_show_animation (NULL, NULL, _("mail_me_opening"));
2395
2396         return FALSE;
2397 }
2398
2399 static void
2400 on_decode_to_stream_async_handler (TnyMimePart *mime_part, 
2401                                    gboolean cancelled, 
2402                                    TnyStream *stream, 
2403                                    GError *err, 
2404                                    gpointer user_data)
2405 {
2406         DecodeAsyncHelper *helper = (DecodeAsyncHelper *) user_data;
2407
2408         if (helper->banner_idle_id > 0) {
2409                 g_source_remove (helper->banner_idle_id);
2410                 helper->banner_idle_id = 0;
2411         }
2412         if (helper->banner) {
2413                 gtk_widget_destroy (helper->banner);
2414                 helper->banner = NULL;
2415         }
2416         if (cancelled || err) {
2417                 modest_platform_information_banner (NULL, NULL, 
2418                                                     _("mail_ib_file_operation_failed"));
2419                 goto free;
2420         }
2421
2422         /* make the file read-only */
2423         g_chmod(helper->filepath, 0444);
2424
2425         /* Activate the file */
2426         modest_platform_activate_file (helper->filepath, tny_mime_part_get_content_type (mime_part));
2427
2428  free:
2429         /* Frees */
2430         g_free (helper->filepath);
2431         g_slice_free (DecodeAsyncHelper, helper);
2432 }
2433
2434 void
2435 modest_msg_view_window_view_attachment (ModestMsgViewWindow *window, 
2436                                         TnyMimePart *mime_part)
2437 {
2438         ModestMsgViewWindowPrivate *priv;
2439         const gchar *msg_uid;
2440         gchar *attachment_uid = NULL;
2441         gint attachment_index = 0;
2442         TnyList *attachments;
2443
2444         g_return_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window));
2445         g_return_if_fail (TNY_IS_MIME_PART (mime_part) || (mime_part == NULL));
2446         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
2447
2448         msg_uid = modest_msg_view_window_get_message_uid (MODEST_MSG_VIEW_WINDOW (window));
2449         attachments = modest_msg_view_get_attachments (MODEST_MSG_VIEW (priv->msg_view));
2450         attachment_index = modest_list_index (attachments, (GObject *) mime_part);
2451         g_object_unref (attachments);
2452         
2453         if (msg_uid && attachment_index >= 0) {
2454                 attachment_uid = g_strdup_printf ("%s/%d", msg_uid, attachment_index);
2455         }
2456
2457         if (mime_part == NULL) {
2458                 gboolean error = FALSE;
2459                 TnyList *selected_attachments = modest_msg_view_get_selected_attachments (MODEST_MSG_VIEW (priv->msg_view));
2460                 if (selected_attachments == NULL || tny_list_get_length (selected_attachments) == 0) {
2461                         error = TRUE;
2462                 } else if (tny_list_get_length (selected_attachments) > 1) {
2463                         hildon_banner_show_information (NULL, NULL, _("mcen_ib_unable_to_display_more"));
2464                         error = TRUE;
2465                 } else {
2466                         TnyIterator *iter;
2467                         iter = tny_list_create_iterator (selected_attachments);
2468                         mime_part = (TnyMimePart *) tny_iterator_get_current (iter);
2469                         g_object_unref (iter);
2470                 }
2471                 g_object_unref (selected_attachments);
2472
2473                 if (error)
2474                         return;
2475         } else {
2476                 g_object_ref (mime_part);
2477         }
2478
2479         if (tny_mime_part_is_purged (mime_part)) {
2480                 g_object_unref (mime_part);
2481                 return;
2482         }
2483
2484         if (!modest_tny_mime_part_is_msg (mime_part)) {
2485                 gchar *filepath = NULL;
2486                 const gchar *att_filename = tny_mime_part_get_filename (mime_part);
2487                 gboolean show_error_banner = FALSE;
2488                 TnyFsStream *temp_stream = NULL;
2489                 temp_stream = modest_utils_create_temp_stream (att_filename, attachment_uid,
2490                                                                &filepath);
2491                 
2492                 if (temp_stream != NULL) {
2493                         DecodeAsyncHelper *helper = g_slice_new (DecodeAsyncHelper);
2494                         helper->filepath = g_strdup (filepath);
2495                         helper->banner = NULL;
2496                         helper->banner_idle_id = g_timeout_add (1000, decode_async_banner_idle, helper);
2497                         tny_mime_part_decode_to_stream_async (mime_part, TNY_STREAM (temp_stream), 
2498                                                               on_decode_to_stream_async_handler, 
2499                                                               NULL, 
2500                                                               helper);
2501                         g_object_unref (temp_stream);
2502                         /* NOTE: files in the temporary area will be automatically
2503                          * cleaned after some time if they are no longer in use */
2504                 } else {
2505                         if (filepath) {
2506                                 const gchar *content_type;
2507                                 /* the file may already exist but it isn't writable,
2508                                  * let's try to open it anyway */
2509                                 content_type = tny_mime_part_get_content_type (mime_part);
2510                                 modest_platform_activate_file (filepath, content_type);
2511                         } else {
2512                                 g_warning ("%s: modest_utils_create_temp_stream failed", __FUNCTION__);
2513                                 show_error_banner = TRUE;
2514                         }
2515                 }
2516                 if (filepath)
2517                         g_free (filepath);
2518                 if (show_error_banner)
2519                         modest_platform_information_banner (NULL, NULL, _("mail_ib_file_operation_failed"));
2520         } else {
2521                 /* message attachment */
2522                 TnyHeader *header = NULL;
2523                 ModestWindowMgr *mgr;
2524                 ModestWindow *msg_win = NULL;
2525                 gboolean found;
2526
2527                 header = tny_msg_get_header (TNY_MSG (mime_part));
2528                 mgr = modest_runtime_get_window_mgr ();
2529                 found = modest_window_mgr_find_registered_header (mgr, header, &msg_win);
2530
2531                 if (found) {
2532                         /* if it's found, but there is no msg_win, it's probably in the process of being created;
2533                          * thus, we don't do anything */
2534                         g_warning ("window for is already being created");
2535                 } else {
2536                         /* it's not found, so create a new window for it */
2537                         modest_window_mgr_register_header (mgr, header, attachment_uid); /* register the uid before building the window */
2538                         gchar *account = g_strdup (modest_window_get_active_account (MODEST_WINDOW (window)));
2539                         if (!account)
2540                                 account = modest_account_mgr_get_default_account (modest_runtime_get_account_mgr ());
2541                         msg_win = modest_msg_view_window_new_for_attachment (TNY_MSG (mime_part), account, attachment_uid);
2542                         modest_window_set_zoom (MODEST_WINDOW (msg_win),
2543                                                 modest_window_get_zoom (MODEST_WINDOW (window)));
2544                         modest_window_mgr_register_window (mgr, msg_win, MODEST_WINDOW (window));
2545                         gtk_widget_show_all (GTK_WIDGET (msg_win));
2546                 }
2547         }
2548         g_object_unref (mime_part);
2549 }
2550
2551 typedef struct
2552 {
2553         gchar *filename;
2554         TnyMimePart *part;
2555 } SaveMimePartPair;
2556
2557 typedef struct
2558 {
2559         GList *pairs;
2560         GtkWidget *banner;
2561         GnomeVFSResult result;
2562 } SaveMimePartInfo;
2563
2564 static void save_mime_part_info_free (SaveMimePartInfo *info, gboolean with_struct);
2565 static gboolean idle_save_mime_part_show_result (SaveMimePartInfo *info);
2566 static gpointer save_mime_part_to_file (SaveMimePartInfo *info);
2567 static void save_mime_parts_to_file_with_checks (SaveMimePartInfo *info);
2568
2569 static void 
2570 save_mime_part_info_free (SaveMimePartInfo *info, gboolean with_struct)
2571 {
2572         
2573         GList *node;
2574         for (node = info->pairs; node != NULL; node = g_list_next (node)) {
2575                 SaveMimePartPair *pair = (SaveMimePartPair *) node->data;
2576                 g_free (pair->filename);
2577                 g_object_unref (pair->part);
2578                 g_slice_free (SaveMimePartPair, pair);
2579         }
2580         g_list_free (info->pairs);
2581         info->pairs = NULL;
2582         if (with_struct) {
2583                 gtk_widget_destroy (info->banner);
2584                 g_slice_free (SaveMimePartInfo, info);
2585         }
2586 }
2587
2588 static gboolean
2589 idle_save_mime_part_show_result (SaveMimePartInfo *info)
2590 {
2591         if (info->pairs != NULL) {
2592                 save_mime_part_to_file (info);
2593         } else {
2594                 /* This is a GDK lock because we are an idle callback and
2595                  * hildon_banner_show_information is or does Gtk+ code */
2596
2597                 gdk_threads_enter (); /* CHECKED */
2598                 save_mime_part_info_free (info, TRUE);
2599                 if (info->result == GNOME_VFS_OK) {
2600                         hildon_banner_show_information (NULL, NULL, _CS("sfil_ib_saved"));
2601                 } else if (info->result == GNOME_VFS_ERROR_NO_SPACE) {
2602                         hildon_banner_show_information (NULL, NULL, dgettext("ke-recv", 
2603                                                                              "cerm_device_memory_full"));
2604                 } else {
2605                         hildon_banner_show_information (NULL, NULL, _("mail_ib_file_operation_failed"));
2606                 }
2607                 gdk_threads_leave (); /* CHECKED */
2608         }
2609
2610         return FALSE;
2611 }
2612
2613 static gpointer
2614 save_mime_part_to_file (SaveMimePartInfo *info)
2615 {
2616         GnomeVFSHandle *handle;
2617         TnyStream *stream;
2618         SaveMimePartPair *pair = (SaveMimePartPair *) info->pairs->data;
2619
2620         info->result = gnome_vfs_create (&handle, pair->filename, GNOME_VFS_OPEN_WRITE, FALSE, 0644);
2621         if (info->result == GNOME_VFS_OK) {
2622                 GError *error = NULL;
2623                 stream = tny_vfs_stream_new (handle);
2624                 if (tny_mime_part_decode_to_stream (pair->part, stream, &error) < 0) {
2625                         g_warning ("modest: could not save attachment %s: %d (%s)\n", pair->filename, error?error->code:-1, error?error->message:"Unknown error");
2626                         
2627                         info->result = GNOME_VFS_ERROR_IO;
2628                 }
2629                 g_object_unref (G_OBJECT (stream));
2630                 g_object_unref (pair->part);
2631                 g_slice_free (SaveMimePartPair, pair);
2632                 info->pairs = g_list_delete_link (info->pairs, info->pairs);
2633         } else {
2634                 g_warning ("modest: could not create save attachment %s: %s\n", pair->filename, gnome_vfs_result_to_string (info->result));
2635                 save_mime_part_info_free (info, FALSE);
2636         }
2637
2638         g_idle_add ((GSourceFunc) idle_save_mime_part_show_result, info);
2639         return NULL;
2640 }
2641
2642 static void
2643 save_mime_parts_to_file_with_checks (SaveMimePartInfo *info)
2644 {
2645         gboolean is_ok = TRUE;
2646         gint replaced_files = 0;
2647         const GList *files = info->pairs;
2648         const GList *iter;
2649
2650         for (iter = files; (iter != NULL) && (replaced_files < 2); iter = g_list_next(iter)) {
2651                 SaveMimePartPair *pair = iter->data;
2652                 if (modest_utils_file_exists (pair->filename)) {
2653                         replaced_files++;
2654                 }
2655         }
2656         if (replaced_files) {
2657                 GtkWidget *confirm_overwrite_dialog;
2658                 const gchar *message = (replaced_files == 1) ?
2659                         _FM("docm_nc_replace_file") : _FM("docm_nc_replace_multiple");
2660                 confirm_overwrite_dialog = hildon_note_new_confirmation (NULL, message);
2661                 if (gtk_dialog_run (GTK_DIALOG (confirm_overwrite_dialog)) != GTK_RESPONSE_OK) {
2662                         is_ok = FALSE;
2663                 }
2664                 gtk_widget_destroy (confirm_overwrite_dialog);
2665         }
2666
2667         if (!is_ok) {
2668                 save_mime_part_info_free (info, TRUE);
2669         } else {
2670                 GtkWidget *banner = hildon_banner_show_animation (NULL, NULL, 
2671                                                                   _CS("sfil_ib_saving"));
2672                 info->banner = banner;
2673                 g_thread_create ((GThreadFunc)save_mime_part_to_file, info, FALSE, NULL);
2674         }
2675
2676 }
2677
2678 static void
2679 save_attachments_response (GtkDialog *dialog,
2680                            gint       arg1,
2681                            gpointer   user_data)  
2682 {
2683         TnyList *mime_parts;
2684         gchar *chooser_uri;
2685         GList *files_to_save = NULL;
2686
2687         mime_parts = TNY_LIST (user_data);
2688
2689         if (arg1 != GTK_RESPONSE_OK)
2690                 goto end;
2691
2692         chooser_uri = gtk_file_chooser_get_uri (GTK_FILE_CHOOSER (dialog));
2693
2694         if (!modest_utils_folder_writable (chooser_uri)) {
2695                 hildon_banner_show_information 
2696                         (NULL, NULL, dgettext("hildon-fm", "sfil_ib_readonly_location"));
2697         } else {
2698                 TnyIterator *iter;
2699
2700                 iter = tny_list_create_iterator (mime_parts);
2701                 while (!tny_iterator_is_done (iter)) {
2702                         TnyMimePart *mime_part = (TnyMimePart *) tny_iterator_get_current (iter);
2703
2704                         if ((modest_tny_mime_part_is_attachment_for_modest (mime_part)) &&
2705                             !tny_mime_part_is_purged (mime_part) &&
2706                             (tny_mime_part_get_filename (mime_part) != NULL)) {
2707                                 SaveMimePartPair *pair;
2708                                         
2709                                 pair = g_slice_new0 (SaveMimePartPair);
2710
2711                                 if (tny_list_get_length (mime_parts) > 1) {
2712                                         gchar *escaped = 
2713                                                 gnome_vfs_escape_slashes (tny_mime_part_get_filename (mime_part));
2714                                         pair->filename = g_build_filename (chooser_uri, escaped, NULL);
2715                                         g_free (escaped);
2716                                 } else {
2717                                         pair->filename = g_strdup (chooser_uri);
2718                                 }
2719                                 pair->part = mime_part;
2720                                 files_to_save = g_list_prepend (files_to_save, pair);
2721                         }
2722                         tny_iterator_next (iter);
2723                 }
2724                 g_object_unref (iter);
2725         }
2726         g_free (chooser_uri);
2727
2728         if (files_to_save != NULL) {
2729                 SaveMimePartInfo *info = g_slice_new0 (SaveMimePartInfo);
2730                 info->pairs = files_to_save;
2731                 info->result = TRUE;
2732                 save_mime_parts_to_file_with_checks (info);
2733         }
2734
2735  end:
2736         /* Free and close the dialog */
2737         g_object_unref (mime_parts);
2738         gtk_widget_destroy (GTK_WIDGET (dialog));
2739 }
2740
2741 void
2742 modest_msg_view_window_save_attachments (ModestMsgViewWindow *window, TnyList *mime_parts)
2743 {
2744         ModestMsgViewWindowPrivate *priv;
2745         GtkWidget *save_dialog = NULL;
2746         gchar *folder = NULL;
2747         gchar *filename = NULL;
2748         gchar *save_multiple_str = NULL;
2749
2750         g_return_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window));
2751         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
2752
2753         if (mime_parts == NULL) {
2754                 mime_parts = modest_msg_view_get_selected_attachments (MODEST_MSG_VIEW (priv->msg_view));
2755                 if (mime_parts == NULL || tny_list_get_length (mime_parts) == 0)
2756                         return;
2757         } else {
2758                 g_object_ref (mime_parts);
2759         }
2760
2761         /* prepare dialog */
2762         if (tny_list_get_length (mime_parts) == 1) {
2763                 TnyIterator *iter;
2764                 /* only one attachment selected */
2765                 iter = tny_list_create_iterator (mime_parts);
2766                 TnyMimePart *mime_part = (TnyMimePart *) tny_iterator_get_current (iter);
2767                 g_object_unref (iter);
2768                 if (!modest_tny_mime_part_is_msg (mime_part) && 
2769                     modest_tny_mime_part_is_attachment_for_modest (mime_part) &&
2770                     !tny_mime_part_is_purged (mime_part)) {
2771                         filename = g_strdup (tny_mime_part_get_filename (mime_part));
2772                 } else {
2773                         /* TODO: show any error? */
2774                         g_warning ("Tried to save a non-file attachment");
2775                         g_object_unref (mime_parts);
2776                         return;
2777                 }
2778                 g_object_unref (mime_part);
2779         } else {
2780                 save_multiple_str = g_strdup_printf (_FM("sfil_va_number_of_objects_attachments"), 
2781                                                      tny_list_get_length (mime_parts));
2782         }
2783         
2784         save_dialog = hildon_file_chooser_dialog_new (GTK_WINDOW (window), 
2785                                                       GTK_FILE_CHOOSER_ACTION_SAVE);
2786
2787         /* set folder */
2788         folder = g_build_filename (g_getenv (MYDOCS_ENV), DOCS_FOLDER, NULL);
2789         gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (save_dialog), folder);
2790         g_free (folder);
2791
2792         /* set filename */
2793         if (filename) {
2794                 gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (save_dialog), 
2795                                                    filename);
2796                 g_free (filename);
2797         }
2798
2799         /* if multiple, set multiple string */
2800         if (save_multiple_str) {
2801                 g_object_set (G_OBJECT (save_dialog), "save-multiple", save_multiple_str, NULL);
2802                 gtk_window_set_title (GTK_WINDOW (save_dialog), _FM("sfil_ti_save_objects_files"));
2803         }
2804
2805         /* We must run this asynchronously, because the hildon dialog
2806            performs a gtk_dialog_run by itself which leads to gdk
2807            deadlocks */
2808         g_signal_connect (save_dialog, "response", 
2809                           G_CALLBACK (save_attachments_response), mime_parts);
2810
2811         gtk_widget_show_all (save_dialog);
2812 }
2813
2814 static gboolean
2815 show_remove_attachment_information (gpointer userdata)
2816 {
2817         ModestMsgViewWindow *window = (ModestMsgViewWindow *) userdata;
2818         ModestMsgViewWindowPrivate *priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
2819
2820         /* We're outside the main lock */
2821         gdk_threads_enter ();
2822
2823         if (priv->remove_attachment_banner != NULL) {
2824                 gtk_widget_destroy (priv->remove_attachment_banner);
2825                 g_object_unref (priv->remove_attachment_banner);
2826         }
2827
2828         priv->remove_attachment_banner = g_object_ref (
2829                 hildon_banner_show_animation (NULL, NULL, _("mcen_me_inbox_remove_attachments")));
2830
2831         gdk_threads_leave ();
2832
2833         return FALSE;
2834 }
2835
2836 void
2837 modest_msg_view_window_remove_attachments (ModestMsgViewWindow *window, gboolean get_all)
2838 {
2839         ModestMsgViewWindowPrivate *priv;
2840         TnyList *mime_parts = NULL;
2841         gchar *confirmation_message;
2842         gint response;
2843         gint n_attachments;
2844         TnyMsg *msg;
2845         TnyIterator *iter;
2846
2847         g_return_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window));
2848         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
2849
2850         if (get_all)
2851                 mime_parts = modest_msg_view_get_attachments (MODEST_MSG_VIEW (priv->msg_view));
2852         else
2853                 mime_parts = modest_msg_view_get_selected_attachments (MODEST_MSG_VIEW (priv->msg_view));
2854                 
2855         /* Remove already purged messages from mime parts list */
2856         iter = tny_list_create_iterator (mime_parts);
2857         while (!tny_iterator_is_done (iter)) {
2858                 TnyMimePart *part = TNY_MIME_PART (tny_iterator_get_current (iter));
2859                 tny_iterator_next (iter);
2860                 if (tny_mime_part_is_purged (part)) {
2861                         tny_list_remove (mime_parts, (GObject *) part);
2862                 }
2863                 g_object_unref (part);
2864         }
2865         g_object_unref (iter);
2866
2867         if (tny_list_get_length (mime_parts) == 0) {
2868                 g_object_unref (mime_parts);
2869                 return;
2870         }
2871
2872         n_attachments = tny_list_get_length (mime_parts);
2873         if (n_attachments == 1) {
2874                 gchar *filename;
2875                 TnyMimePart *part;
2876
2877                 iter = tny_list_create_iterator (mime_parts);
2878                 part = (TnyMimePart *) tny_iterator_get_current (iter);
2879                 g_object_unref (iter);
2880                 if (modest_tny_mime_part_is_msg (part)) {
2881                         TnyHeader *header;
2882                         header = tny_msg_get_header (TNY_MSG (part));
2883                         filename = tny_header_dup_subject (header);
2884                         g_object_unref (header);
2885                         if (filename == NULL)
2886                                 filename = g_strdup (_("mail_va_no_subject"));
2887                 } else {
2888                         filename = g_strdup (tny_mime_part_get_filename (TNY_MIME_PART (part)));
2889                 }
2890                 confirmation_message = g_strdup_printf (_("mcen_nc_purge_file_text"), filename);
2891                 g_free (filename);
2892                 g_object_unref (part);
2893         } else {
2894                 confirmation_message = g_strdup_printf (ngettext("mcen_nc_purge_file_text", 
2895                                                                  "mcen_nc_purge_files_text", 
2896                                                                  n_attachments), n_attachments);
2897         }
2898         response = modest_platform_run_confirmation_dialog (GTK_WINDOW (window),
2899                                                             confirmation_message);
2900         g_free (confirmation_message);
2901
2902         if (response != GTK_RESPONSE_OK) {
2903                 g_object_unref (mime_parts);
2904                 return;
2905         }
2906
2907         priv->purge_timeout = g_timeout_add (2000, show_remove_attachment_information, window);
2908         
2909         iter = tny_list_create_iterator (mime_parts);
2910         while (!tny_iterator_is_done (iter)) {
2911                 TnyMimePart *part;
2912
2913                 part = (TnyMimePart *) tny_iterator_get_current (iter);
2914                 tny_mime_part_set_purged (TNY_MIME_PART (part));
2915                 g_object_unref (part);
2916                 tny_iterator_next (iter);
2917         }
2918         g_object_unref (iter);
2919
2920         msg = tny_msg_view_get_msg (TNY_MSG_VIEW (priv->msg_view));
2921         tny_msg_view_clear (TNY_MSG_VIEW (priv->msg_view));
2922         tny_msg_rewrite_cache (msg);
2923         tny_msg_view_set_msg (TNY_MSG_VIEW (priv->msg_view), msg);
2924         g_object_unref (msg);
2925
2926         g_object_unref (mime_parts);
2927
2928         if (priv->purge_timeout > 0) {
2929                 g_source_remove (priv->purge_timeout);
2930                 priv->purge_timeout = 0;
2931         }
2932
2933         if (priv->remove_attachment_banner) {
2934                 gtk_widget_destroy (priv->remove_attachment_banner);
2935                 g_object_unref (priv->remove_attachment_banner);
2936                 priv->remove_attachment_banner = NULL;
2937         }
2938
2939
2940 }
2941
2942
2943 static void
2944 update_window_title (ModestMsgViewWindow *window)
2945 {
2946         ModestMsgViewWindowPrivate *priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
2947         TnyMsg *msg = NULL;
2948         TnyHeader *header = NULL;
2949         gchar *subject = NULL;
2950         
2951         msg = tny_msg_view_get_msg (TNY_MSG_VIEW (priv->msg_view));
2952
2953         if (msg != NULL) {
2954                 header = tny_msg_get_header (msg);
2955                 subject = tny_header_dup_subject (header);
2956                 g_object_unref (header);
2957                 g_object_unref (msg);
2958         }
2959
2960         if ((subject == NULL)||(subject[0] == '\0')) {
2961                 g_free (subject);
2962                 subject = g_strdup (_("mail_va_no_subject"));
2963         }
2964
2965         gtk_window_set_title (GTK_WINDOW (window), subject);
2966 }
2967
2968
2969 static void on_move_focus (GtkWidget *widget,
2970                            GtkDirectionType direction,
2971                            gpointer userdata)
2972 {
2973         g_signal_stop_emission_by_name (G_OBJECT (widget), "move-focus");
2974 }
2975
2976 static TnyStream *
2977 fetch_image_open_stream (TnyStreamCache *self, gint64 *expected_size, gchar *uri)
2978 {
2979         GnomeVFSResult result;
2980         GnomeVFSHandle *handle = NULL;
2981         GnomeVFSFileInfo *info = NULL;
2982         TnyStream *stream;
2983
2984         result = gnome_vfs_open (&handle, uri, GNOME_VFS_OPEN_READ);
2985         if (result != GNOME_VFS_OK) {
2986                 *expected_size = 0;
2987                 return NULL;
2988         }
2989         
2990         info = gnome_vfs_file_info_new ();
2991         result = gnome_vfs_get_file_info_from_handle (handle, info, GNOME_VFS_FILE_INFO_DEFAULT);
2992         if (result != GNOME_VFS_OK || ! (info->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_SIZE)) {
2993                 /* We put a "safe" default size for going to cache */
2994                 *expected_size = (300*1024);
2995         } else {
2996                 *expected_size = info->size;
2997         }
2998         gnome_vfs_file_info_unref (info);
2999
3000         stream = tny_vfs_stream_new (handle);
3001
3002         return stream;
3003
3004 }
3005
3006 typedef struct {
3007         gchar *uri;
3008         gchar *cache_id;
3009         TnyStream *output_stream;
3010         GtkWidget *msg_view;
3011 } FetchImageData;
3012
3013 gboolean
3014 on_fetch_image_idle_refresh_view (gpointer userdata)
3015 {
3016
3017         FetchImageData *fidata = (FetchImageData *) userdata;
3018         g_message ("REFRESH VIEW");
3019         if (GTK_WIDGET_DRAWABLE (fidata->msg_view)) {
3020                 g_message ("QUEUING DRAW");
3021                 gtk_widget_queue_draw (fidata->msg_view);
3022         }
3023         g_object_unref (fidata->msg_view);
3024         g_slice_free (FetchImageData, fidata);
3025         return FALSE;
3026 }
3027
3028 static gpointer
3029 on_fetch_image_thread (gpointer userdata)
3030 {
3031         FetchImageData *fidata = (FetchImageData *) userdata;
3032         TnyStreamCache *cache;
3033         TnyStream *cache_stream;
3034
3035         cache = modest_runtime_get_images_cache ();
3036         cache_stream = tny_stream_cache_get_stream (cache, fidata->cache_id, (TnyStreamCacheOpenStreamFetcher) fetch_image_open_stream, (gpointer) fidata->uri);
3037         g_free (fidata->cache_id);
3038         g_free (fidata->uri);
3039
3040         if (cache_stream != NULL) {
3041                 tny_stream_write_to_stream (cache_stream, fidata->output_stream);
3042                 tny_stream_close (cache_stream);
3043                 g_object_unref (cache_stream);
3044         }
3045
3046         tny_stream_close (fidata->output_stream);
3047         g_object_unref (fidata->output_stream);
3048
3049
3050         gdk_threads_enter ();
3051         g_idle_add (on_fetch_image_idle_refresh_view, fidata);
3052         gdk_threads_leave ();
3053
3054         return NULL;
3055 }
3056
3057 static gboolean
3058 on_fetch_image (ModestMsgView *msgview,
3059                 const gchar *uri,
3060                 TnyStream *stream,
3061                 ModestMsgViewWindow *window)
3062 {
3063         const gchar *current_account;
3064         ModestMsgViewWindowPrivate *priv;
3065         FetchImageData *fidata;
3066
3067         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
3068
3069         current_account = modest_window_get_active_account (MODEST_WINDOW (window));
3070
3071         fidata = g_slice_new0 (FetchImageData);
3072         fidata->msg_view = g_object_ref (msgview);
3073         fidata->uri = g_strdup (uri);
3074         fidata->cache_id = modest_images_cache_get_id (current_account, uri);
3075         fidata->output_stream = g_object_ref (stream);
3076
3077         if (g_thread_create (on_fetch_image_thread, fidata, FALSE, NULL) == NULL) {
3078                 g_object_unref (fidata->output_stream);
3079                 g_free (fidata->cache_id);
3080                 g_free (fidata->uri);
3081                 g_object_unref (fidata->msg_view);
3082                 g_slice_free (FetchImageData, fidata);
3083                 tny_stream_close (stream);
3084                 return FALSE;
3085         }
3086
3087         return TRUE;;
3088 }
3089
3090 static void 
3091 setup_menu (ModestMsgViewWindow *self)
3092 {
3093         g_return_if_fail (MODEST_IS_MSG_VIEW_WINDOW(self));
3094
3095         /* Settings menu buttons */
3096         modest_hildon2_window_add_to_menu (MODEST_HILDON2_WINDOW (self), _("mcen_me_inbox_replytoall"), NULL,
3097                                            APP_MENU_CALLBACK (modest_ui_actions_on_reply_all),
3098                                            MODEST_DIMMING_CALLBACK (modest_ui_dimming_rules_on_reply_msg));
3099         modest_hildon2_window_add_to_menu (MODEST_HILDON2_WINDOW (self), _("mcen_me_inbox_forward"), "<Control>d",
3100                                            APP_MENU_CALLBACK (modest_ui_actions_on_forward),
3101                                            MODEST_DIMMING_CALLBACK (modest_ui_dimming_rules_on_reply_msg));
3102         
3103         modest_hildon2_window_add_to_menu (MODEST_HILDON2_WINDOW (self), _("mcen_me_inbox_mark_as_read"), NULL,
3104                                            APP_MENU_CALLBACK (modest_ui_actions_on_mark_as_read),
3105                                            MODEST_DIMMING_CALLBACK (modest_ui_dimming_rules_on_mark_as_read_msg_in_view));
3106         modest_hildon2_window_add_to_menu (MODEST_HILDON2_WINDOW (self), _("mcen_me_inbox_mark_as_unread"), NULL,
3107                                            APP_MENU_CALLBACK (modest_ui_actions_on_mark_as_unread),
3108                                            MODEST_DIMMING_CALLBACK (modest_ui_dimming_rules_on_mark_as_unread_msg_in_view));
3109         
3110         modest_hildon2_window_add_to_menu (MODEST_HILDON2_WINDOW (self), _("mcen_me_viewer_save_attachments"), NULL,
3111                                            APP_MENU_CALLBACK (modest_ui_actions_save_attachments),
3112                                            MODEST_DIMMING_CALLBACK (modest_ui_dimming_rules_on_save_attachments));
3113         modest_hildon2_window_add_to_menu (MODEST_HILDON2_WINDOW (self), _("mcen_me_inbox_remove_attachments"), NULL,
3114                                            APP_MENU_CALLBACK (modest_ui_actions_remove_attachments),
3115                                            MODEST_DIMMING_CALLBACK (modest_ui_dimming_rules_on_remove_attachments));
3116         
3117         modest_hildon2_window_add_to_menu (MODEST_HILDON2_WINDOW (self), _("mcen_me_new_message"), "<Control>n",
3118                                            APP_MENU_CALLBACK (modest_ui_actions_on_new_msg),
3119                                            MODEST_DIMMING_CALLBACK (modest_ui_dimming_rules_on_new_msg));
3120         modest_hildon2_window_add_to_menu (MODEST_HILDON2_WINDOW (self), _("mcen_me_viewer_addtocontacts"), NULL,
3121                                            APP_MENU_CALLBACK (modest_ui_actions_add_to_contacts),
3122                                            MODEST_DIMMING_CALLBACK (modest_ui_dimming_rules_on_add_to_contacts));
3123 }
3124
3125 void
3126 modest_msg_view_window_add_to_contacts (ModestMsgViewWindow *self)
3127 {
3128         ModestMsgViewWindowPrivate *priv;
3129         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (self);