Add "updating" title as progress feedback in msg view
[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
1834                 /* We set the header from model while we're loading */
1835                 tny_header_view_set_header (TNY_HEADER_VIEW (priv->msg_view), header);
1836                 gtk_window_set_title (GTK_WINDOW (window), _CS("ckdg_pb_updating"));
1837
1838                 /* Ask the user if he wants to download the message if
1839                    we're not online */
1840                 if (!tny_device_is_online (modest_runtime_get_device())) {
1841                         GtkResponseType response;
1842
1843                         response = modest_platform_run_confirmation_dialog (GTK_WINDOW (window),
1844                                                                             _("mcen_nc_get_msg"));
1845                         if (response == GTK_RESPONSE_CANCEL)
1846                                 return FALSE;
1847                 
1848                         folder = tny_header_get_folder (header);
1849                         info = g_slice_new (MsgReaderInfo);
1850                         info->header = g_object_ref (header);
1851                         info->row_reference = gtk_tree_row_reference_copy (row_reference);
1852
1853                         /* Offer the connection dialog if necessary */
1854                         modest_platform_connect_if_remote_and_perform ((GtkWindow *) window, 
1855                                                                        TRUE,
1856                                                                        TNY_FOLDER_STORE (folder),
1857                                                                        message_reader_performer, 
1858                                                                        info);
1859                         g_object_unref (folder);
1860                         return TRUE;
1861                 }
1862         }
1863         
1864         folder = tny_header_get_folder (header);
1865         account = tny_folder_get_account (folder);
1866         info = g_slice_new (MsgReaderInfo);
1867         info->header = g_object_ref (header);
1868         info->row_reference = gtk_tree_row_reference_copy (row_reference);
1869         
1870         message_reader_performer (FALSE, NULL, (GtkWindow *) window, account, info);
1871         g_object_unref (account);
1872         g_object_unref (folder);
1873
1874         return TRUE;
1875 }
1876
1877 gboolean        
1878 modest_msg_view_window_select_next_message (ModestMsgViewWindow *window)
1879 {
1880         ModestMsgViewWindowPrivate *priv;
1881         GtkTreePath *path= NULL;
1882         GtkTreeIter tmp_iter;
1883         TnyHeader *header;
1884         gboolean retval = TRUE;
1885         GtkTreeRowReference *row_reference = NULL;
1886
1887         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window), FALSE);
1888         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
1889
1890         if (!priv->row_reference)
1891                 return FALSE;
1892
1893         /* Update the next row reference if it's not valid. This could
1894            happen if for example the header which it was pointing to,
1895            was deleted. The best place to do it is in the row-deleted
1896            handler but the tinymail model do not work like the glib
1897            tree models and reports the deletion when the row is still
1898            there */
1899         if (!gtk_tree_row_reference_valid (priv->next_row_reference)) {
1900                 if (gtk_tree_row_reference_valid (priv->row_reference)) {
1901                         priv->next_row_reference = gtk_tree_row_reference_copy (priv->row_reference);
1902                         select_next_valid_row (priv->header_model, &(priv->next_row_reference), FALSE, priv->is_outbox);
1903                 }
1904         }
1905         if (priv->next_row_reference)
1906                 path = gtk_tree_row_reference_get_path (priv->next_row_reference);
1907         if (path == NULL)
1908                 return FALSE;
1909
1910         row_reference = gtk_tree_row_reference_copy (priv->next_row_reference);
1911
1912         gtk_tree_model_get_iter (priv->header_model,
1913                                  &tmp_iter,
1914                                  path);
1915         gtk_tree_path_free (path);
1916
1917         gtk_tree_model_get (priv->header_model, &tmp_iter, 
1918                             TNY_GTK_HEADER_LIST_MODEL_INSTANCE_COLUMN,
1919                             &header, -1);
1920         
1921         /* Read the message & show it */
1922         if (!message_reader (window, priv, header, row_reference)) {
1923                 retval = FALSE;
1924         }
1925         gtk_tree_row_reference_free (row_reference);
1926
1927         /* Free */
1928         g_object_unref (header);
1929
1930         return retval;
1931 }
1932
1933 gboolean        
1934 modest_msg_view_window_select_previous_message (ModestMsgViewWindow *window)
1935 {
1936         ModestMsgViewWindowPrivate *priv = NULL;
1937         GtkTreePath *path;
1938         gboolean finished = FALSE;
1939         gboolean retval = FALSE;
1940
1941         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window), FALSE);
1942         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
1943
1944         /* Return inmediatly if there is no header model */
1945         if (!priv->header_model || !priv->row_reference)
1946                 return FALSE;
1947
1948         path = gtk_tree_row_reference_get_path (priv->row_reference);
1949         while (!finished && gtk_tree_path_prev (path)) {
1950                 TnyHeader *header;
1951                 GtkTreeIter iter;
1952
1953                 gtk_tree_model_get_iter (priv->header_model, &iter, path);
1954                 gtk_tree_model_get (priv->header_model, &iter, 
1955                                     TNY_GTK_HEADER_LIST_MODEL_INSTANCE_COLUMN,
1956                                     &header, -1);
1957                 finished = TRUE;
1958                 if (header) {
1959                         if (msg_is_visible (header, priv->is_outbox)) {
1960                                 GtkTreeRowReference *row_reference;
1961                                 row_reference = gtk_tree_row_reference_new (priv->header_model, path);
1962                                 /* Read the message & show it */
1963                                 retval = message_reader (window, priv, header, row_reference);
1964                                 gtk_tree_row_reference_free (row_reference);
1965                         } else {
1966                                 finished = FALSE;
1967                         }
1968                         g_object_unref (header);
1969                 }
1970         }
1971
1972         gtk_tree_path_free (path);
1973         return retval;
1974 }
1975
1976 static void
1977 view_msg_cb (ModestMailOperation *mail_op, 
1978              TnyHeader *header, 
1979              gboolean canceled,
1980              TnyMsg *msg, 
1981              GError *error,
1982              gpointer user_data)
1983 {
1984         ModestMsgViewWindow *self = NULL;
1985         ModestMsgViewWindowPrivate *priv = NULL;
1986         GtkTreeRowReference *row_reference = NULL;
1987
1988         /* Unregister the header (it was registered before creating the mail operation) */
1989         modest_window_mgr_unregister_header (modest_runtime_get_window_mgr (), header);
1990
1991         row_reference = (GtkTreeRowReference *) user_data;
1992         if (canceled) {
1993                 gtk_tree_row_reference_free (row_reference);
1994                 return;
1995         }
1996         
1997         /* If there was any error */
1998         if (!modest_ui_actions_msg_retrieval_check (mail_op, header, msg)) {
1999                 gtk_tree_row_reference_free (row_reference);                    
2000                 return;
2001         }
2002
2003         /* Get the window */ 
2004         self = (ModestMsgViewWindow *) modest_mail_operation_get_source (mail_op);
2005         g_return_if_fail (MODEST_IS_MSG_VIEW_WINDOW (self));
2006         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (self);
2007
2008         /* Update the row reference */
2009         if (priv->row_reference != NULL) {
2010                 gtk_tree_row_reference_free (priv->row_reference);
2011                 priv->row_reference = gtk_tree_row_reference_copy (row_reference);
2012                 if (priv->next_row_reference != NULL) {
2013                         gtk_tree_row_reference_free (priv->next_row_reference);
2014                 }
2015                 priv->next_row_reference = gtk_tree_row_reference_copy (priv->row_reference);
2016                 select_next_valid_row (priv->header_model, &(priv->next_row_reference), TRUE, priv->is_outbox);
2017         }
2018
2019         /* Mark header as read */
2020         if (!(tny_header_get_flags (header) & TNY_HEADER_FLAG_SEEN))
2021                 tny_header_set_flag (header, TNY_HEADER_FLAG_SEEN);
2022
2023         /* Set new message */
2024         if (priv->msg_view != NULL && TNY_IS_MSG_VIEW (priv->msg_view)) {
2025                 tny_msg_view_set_msg (TNY_MSG_VIEW (priv->msg_view), msg);
2026                 modest_msg_view_window_update_priority (self);
2027                 update_window_title (MODEST_MSG_VIEW_WINDOW (self));
2028                 modest_msg_view_grab_focus (MODEST_MSG_VIEW (priv->msg_view));
2029         }
2030
2031         /* Set the new message uid of the window  */
2032         if (priv->msg_uid) {
2033                 g_free (priv->msg_uid);
2034                 priv->msg_uid = modest_tny_folder_get_header_unique_id (header);
2035         }
2036
2037         /* Notify the observers */
2038         g_signal_emit (G_OBJECT (self), signals[MSG_CHANGED_SIGNAL], 
2039                        0, priv->header_model, priv->row_reference);
2040
2041         /* Frees */
2042         g_object_unref (self);
2043         gtk_tree_row_reference_free (row_reference);            
2044 }
2045
2046 TnyFolderType
2047 modest_msg_view_window_get_folder_type (ModestMsgViewWindow *window)
2048 {
2049         ModestMsgViewWindowPrivate *priv;
2050         TnyMsg *msg;
2051         TnyFolderType folder_type;
2052
2053         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
2054
2055         folder_type = TNY_FOLDER_TYPE_UNKNOWN;
2056
2057         msg = tny_msg_view_get_msg (TNY_MSG_VIEW (priv->msg_view));
2058         if (msg) {
2059                 TnyFolder *folder;
2060
2061                 folder = tny_msg_get_folder (msg);
2062                 if (folder) {
2063                         folder_type = modest_tny_folder_guess_folder_type (folder);
2064                         g_object_unref (folder);
2065                 }
2066                 g_object_unref (msg);
2067         }
2068
2069         return folder_type;
2070 }
2071
2072
2073 static void
2074 modest_msg_view_window_update_priority (ModestMsgViewWindow *window)
2075 {
2076         ModestMsgViewWindowPrivate *priv;
2077         TnyHeader *header = NULL;
2078         TnyHeaderFlags flags = 0;
2079
2080         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
2081
2082         if (priv->header_model && priv->row_reference) {
2083                 GtkTreeIter iter;
2084                 GtkTreePath *path = NULL;
2085
2086                 path = gtk_tree_row_reference_get_path (priv->row_reference);
2087                 g_return_if_fail (path != NULL);
2088                 gtk_tree_model_get_iter (priv->header_model, 
2089                                          &iter, 
2090                                          gtk_tree_row_reference_get_path (priv->row_reference));
2091
2092                 gtk_tree_model_get (priv->header_model, &iter, TNY_GTK_HEADER_LIST_MODEL_INSTANCE_COLUMN,
2093                                     &header, -1);
2094                 gtk_tree_path_free (path);
2095         } else {
2096                 TnyMsg *msg;
2097                 msg = tny_msg_view_get_msg (TNY_MSG_VIEW (priv->msg_view));
2098                 if (msg) {
2099                         header = tny_msg_get_header (msg);
2100                         g_object_unref (msg);
2101                 }
2102         }
2103
2104         if (header) {
2105                 flags = tny_header_get_flags (header);
2106                 g_object_unref(G_OBJECT(header));
2107         }
2108
2109         modest_msg_view_set_priority (MODEST_MSG_VIEW(priv->msg_view), flags);
2110
2111 }
2112
2113 static void
2114 toolbar_resize (ModestMsgViewWindow *self)
2115 {
2116         ModestMsgViewWindowPrivate *priv = NULL;
2117         ModestWindowPrivate *parent_priv = NULL;
2118         GtkWidget *widget;
2119         gint static_button_size;
2120         ModestWindowMgr *mgr;
2121
2122         g_return_if_fail (MODEST_IS_MSG_VIEW_WINDOW (self));
2123         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (self);
2124         parent_priv = MODEST_WINDOW_GET_PRIVATE(self);
2125
2126         mgr = modest_runtime_get_window_mgr ();
2127         static_button_size = modest_window_mgr_get_fullscreen_mode (mgr)?118:108;
2128
2129         if (parent_priv->toolbar) {
2130                 /* left size buttons */
2131                 widget = gtk_ui_manager_get_widget (parent_priv->ui_manager, "/ToolBar/ToolbarMessageReply");
2132                 gtk_tool_item_set_expand (GTK_TOOL_ITEM (widget), FALSE);
2133                 gtk_tool_item_set_homogeneous (GTK_TOOL_ITEM (widget), FALSE);
2134                 gtk_widget_set_size_request (GTK_WIDGET (widget), static_button_size, -1);
2135                 widget = gtk_ui_manager_get_widget (parent_priv->ui_manager, "/ToolBar/ToolbarMessageMoveTo");
2136                 gtk_tool_item_set_expand (GTK_TOOL_ITEM (widget), FALSE);
2137                 gtk_tool_item_set_homogeneous (GTK_TOOL_ITEM (widget), FALSE);
2138                 gtk_widget_set_size_request (GTK_WIDGET (widget), static_button_size, -1);
2139                 widget = gtk_ui_manager_get_widget (parent_priv->ui_manager, "/ToolBar/ToolbarDeleteMessage");
2140                 gtk_tool_item_set_expand (GTK_TOOL_ITEM (widget), FALSE);
2141                 gtk_tool_item_set_homogeneous (GTK_TOOL_ITEM (widget), FALSE);
2142                 gtk_widget_set_size_request (GTK_WIDGET (widget), static_button_size, -1);
2143                 widget = gtk_ui_manager_get_widget (parent_priv->ui_manager, "/ToolBar/FindInMessage");
2144                 gtk_tool_item_set_expand (GTK_TOOL_ITEM (widget), FALSE);
2145                 gtk_tool_item_set_homogeneous (GTK_TOOL_ITEM (widget), FALSE);
2146                 gtk_widget_set_size_request (GTK_WIDGET (widget), static_button_size, -1);
2147                 
2148                 gtk_tool_item_set_homogeneous (GTK_TOOL_ITEM (priv->next_toolitem), TRUE);
2149                 gtk_tool_item_set_expand (GTK_TOOL_ITEM (priv->next_toolitem), TRUE);
2150                 gtk_tool_item_set_homogeneous (GTK_TOOL_ITEM (priv->prev_toolitem), TRUE);
2151                 gtk_tool_item_set_expand (GTK_TOOL_ITEM (priv->prev_toolitem), TRUE);
2152         }
2153                 
2154 }
2155
2156 static void
2157 modest_msg_view_window_show_toolbar (ModestWindow *self,
2158                                      gboolean show_toolbar)
2159 {
2160         ModestMsgViewWindowPrivate *priv = NULL;
2161         ModestWindowPrivate *parent_priv;
2162         GtkWidget *reply_button = NULL, *menu = NULL;
2163
2164         parent_priv = MODEST_WINDOW_GET_PRIVATE(self);
2165         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE(self);
2166
2167         /* Set optimized view status */
2168         priv->optimized_view = !show_toolbar;
2169
2170         if (!parent_priv->toolbar) {
2171                 parent_priv->toolbar = gtk_ui_manager_get_widget (parent_priv->ui_manager, 
2172                                                                   "/ToolBar");
2173                 gtk_widget_set_no_show_all (parent_priv->toolbar, TRUE);
2174
2175                 priv->next_toolitem = gtk_ui_manager_get_widget (parent_priv->ui_manager, "/ToolBar/ToolbarMessageNext");
2176                 priv->prev_toolitem = gtk_ui_manager_get_widget (parent_priv->ui_manager, "/ToolBar/ToolbarMessageBack");
2177                 toolbar_resize (MODEST_MSG_VIEW_WINDOW (self));
2178
2179                 /* Add to window */
2180                 hildon_window_add_toolbar (HILDON_WINDOW (self), 
2181                                            GTK_TOOLBAR (parent_priv->toolbar));
2182
2183                 /* Set reply button tap and hold menu */
2184                 reply_button = gtk_ui_manager_get_widget (parent_priv->ui_manager, 
2185                                                           "/ToolBar/ToolbarMessageReply");
2186                 menu = gtk_ui_manager_get_widget (parent_priv->ui_manager, 
2187                                                   "/ToolbarReplyCSM");
2188                 if (menu && reply_button)
2189                         gtk_widget_tap_and_hold_setup (GTK_WIDGET (reply_button), menu, NULL, 0);
2190         }
2191
2192         if (show_toolbar) {
2193                 /* Quick hack: this prevents toolbar icons "dance" when progress bar show status is changed */ 
2194                 /* TODO: resize mode migth be GTK_RESIZE_QUEUE, in order to avoid unneccesary shows */
2195                 gtk_container_set_resize_mode (GTK_CONTAINER(parent_priv->toolbar), GTK_RESIZE_IMMEDIATE);
2196
2197                 gtk_widget_show (GTK_WIDGET (parent_priv->toolbar));
2198                 if (modest_msg_view_window_transfer_mode_enabled (MODEST_MSG_VIEW_WINDOW (self))) 
2199                         set_progress_hint (MODEST_MSG_VIEW_WINDOW (self), TRUE);
2200                 else
2201                         set_progress_hint (MODEST_MSG_VIEW_WINDOW (self), FALSE);
2202
2203         } else {
2204                 gtk_widget_set_no_show_all (parent_priv->toolbar, TRUE);
2205                 gtk_widget_hide (GTK_WIDGET (parent_priv->toolbar));
2206         }
2207 }
2208
2209 static void 
2210 modest_msg_view_window_clipboard_owner_change (GtkClipboard *clipboard,
2211                                                GdkEvent *event,
2212                                                ModestMsgViewWindow *window)
2213 {
2214         if (!GTK_WIDGET_VISIBLE (window))
2215                 return;
2216
2217         modest_window_check_dimming_rules_group (MODEST_WINDOW (window), MODEST_DIMMING_RULES_CLIPBOARD);
2218 }
2219
2220 gboolean 
2221 modest_msg_view_window_transfer_mode_enabled (ModestMsgViewWindow *self)
2222 {
2223         ModestMsgViewWindowPrivate *priv;
2224         
2225         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (self), FALSE); 
2226         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE(self);
2227
2228         return priv->progress_hint;
2229 }
2230
2231 static gboolean
2232 observers_empty (ModestMsgViewWindow *self)
2233 {
2234         GSList *tmp = NULL;
2235         ModestMsgViewWindowPrivate *priv;
2236         gboolean is_empty = TRUE;
2237         guint pending_ops = 0;
2238  
2239         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE(self);
2240         tmp = priv->progress_widgets;
2241
2242         /* Check all observers */
2243         while (tmp && is_empty)  {
2244                 pending_ops = modest_progress_object_num_pending_operations (MODEST_PROGRESS_OBJECT(tmp->data));
2245                 is_empty = pending_ops == 0;
2246                 
2247                 tmp = g_slist_next(tmp);
2248         }
2249         
2250         return is_empty;
2251 }
2252
2253 static void
2254 on_account_removed (TnyAccountStore *account_store, 
2255                     TnyAccount *account,
2256                     gpointer user_data)
2257 {
2258         /* Do nothing if it's a transport account, because we only
2259            show the messages of a store account */
2260         if (tny_account_get_account_type(account) == TNY_ACCOUNT_TYPE_STORE) {
2261                 const gchar *parent_acc = NULL;
2262                 const gchar *our_acc = NULL;
2263
2264                 our_acc = modest_window_get_active_account (MODEST_WINDOW (user_data));
2265                 parent_acc = modest_tny_account_get_parent_modest_account_name_for_server_account (account);
2266
2267                 /* Close this window if I'm showing a message of the removed account */
2268                 if (strcmp (parent_acc, our_acc) == 0)
2269                         modest_ui_actions_on_close_window (NULL, MODEST_WINDOW (user_data));
2270         }
2271 }
2272
2273 static void 
2274 on_mail_operation_started (ModestMailOperation *mail_op,
2275                            gpointer user_data)
2276 {
2277         ModestMsgViewWindow *self;
2278         ModestMailOperationTypeOperation op_type;
2279         GSList *tmp;
2280         ModestMsgViewWindowPrivate *priv;
2281         GObject *source = NULL;
2282
2283         self = MODEST_MSG_VIEW_WINDOW (user_data);
2284         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (self);
2285         op_type = modest_mail_operation_get_type_operation (mail_op);
2286         tmp = priv->progress_widgets;
2287         source = modest_mail_operation_get_source(mail_op);
2288         if (G_OBJECT (self) == source) {
2289                 if (op_type == MODEST_MAIL_OPERATION_TYPE_RECEIVE ) {
2290                         set_toolbar_transfer_mode(self);
2291                         while (tmp) {
2292                                 modest_progress_object_add_operation (
2293                                                 MODEST_PROGRESS_OBJECT (tmp->data),
2294                                                 mail_op);
2295                                 tmp = g_slist_next (tmp);
2296                         }
2297                 }
2298         }
2299         g_object_unref (source);
2300 }
2301
2302 static void 
2303 on_mail_operation_finished (ModestMailOperation *mail_op,
2304                             gpointer user_data)
2305 {
2306         ModestMsgViewWindow *self;
2307         ModestMailOperationTypeOperation op_type;
2308         GSList *tmp;
2309         ModestMsgViewWindowPrivate *priv;
2310         
2311         self = MODEST_MSG_VIEW_WINDOW (user_data);
2312         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (self);
2313         op_type = modest_mail_operation_get_type_operation (mail_op);
2314         tmp = priv->progress_widgets;
2315         
2316         if (op_type == MODEST_MAIL_OPERATION_TYPE_RECEIVE ) {
2317                 while (tmp) {
2318                         modest_progress_object_remove_operation (MODEST_PROGRESS_OBJECT (tmp->data),
2319                                                                  mail_op);
2320                         tmp = g_slist_next (tmp);
2321                 }
2322
2323                 /* If no more operations are being observed, NORMAL mode is enabled again */
2324                 if (observers_empty (self)) {
2325                         set_progress_hint (self, FALSE);
2326                 }
2327
2328                 /* Update dimming rules. We have to do this right here
2329                    and not in view_msg_cb because at that point the
2330                    transfer mode is still enabled so the dimming rule
2331                    won't let the user delete the message that has been
2332                    readed for example */
2333                 modest_ui_actions_check_toolbar_dimming_rules (MODEST_WINDOW (self));
2334                 modest_ui_actions_check_menu_dimming_rules (MODEST_WINDOW (self));
2335         }
2336 }
2337
2338 static void
2339 on_queue_changed (ModestMailOperationQueue *queue,
2340                   ModestMailOperation *mail_op,
2341                   ModestMailOperationQueueNotification type,
2342                   ModestMsgViewWindow *self)
2343 {       
2344         ModestMsgViewWindowPrivate *priv;
2345
2346         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (self);
2347
2348         /* If this operations was created by another window, do nothing */
2349         if (!modest_mail_operation_is_mine (mail_op, G_OBJECT(self))) 
2350             return;
2351
2352         if (type == MODEST_MAIL_OPERATION_QUEUE_OPERATION_ADDED) {
2353                 priv->sighandlers = modest_signal_mgr_connect (priv->sighandlers,
2354                                                                G_OBJECT (mail_op),
2355                                                                "operation-started",
2356                                                                G_CALLBACK (on_mail_operation_started),
2357                                                                self);
2358                 priv->sighandlers = modest_signal_mgr_connect (priv->sighandlers,
2359                                                                G_OBJECT (mail_op),
2360                                                                "operation-finished",
2361                                                                G_CALLBACK (on_mail_operation_finished),
2362                                                                self);
2363         } else if (type == MODEST_MAIL_OPERATION_QUEUE_OPERATION_REMOVED) {
2364                 priv->sighandlers = modest_signal_mgr_disconnect (priv->sighandlers,
2365                                                                   G_OBJECT (mail_op),
2366                                                                   "operation-started");
2367                 priv->sighandlers = modest_signal_mgr_disconnect (priv->sighandlers,
2368                                                                   G_OBJECT (mail_op),
2369                                                                   "operation-finished");
2370         }
2371 }
2372
2373 TnyList *
2374 modest_msg_view_window_get_attachments (ModestMsgViewWindow *win) 
2375 {
2376         ModestMsgViewWindowPrivate *priv;
2377         TnyList *selected_attachments = NULL;
2378         
2379         g_return_val_if_fail (MODEST_IS_MSG_VIEW_WINDOW (win), NULL);
2380         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (win);
2381
2382         selected_attachments = modest_msg_view_get_selected_attachments (MODEST_MSG_VIEW (priv->msg_view));
2383         
2384         return selected_attachments;
2385 }
2386
2387 typedef struct {
2388         gchar *filepath;
2389         GtkWidget *banner;
2390         guint banner_idle_id;
2391 } DecodeAsyncHelper;
2392
2393 static gboolean
2394 decode_async_banner_idle (gpointer user_data)
2395 {
2396         DecodeAsyncHelper *helper = (DecodeAsyncHelper *) user_data;
2397
2398         helper->banner_idle_id = 0;
2399         helper->banner = hildon_banner_show_animation (NULL, NULL, _("mail_me_opening"));
2400
2401         return FALSE;
2402 }
2403
2404 static void
2405 on_decode_to_stream_async_handler (TnyMimePart *mime_part, 
2406                                    gboolean cancelled, 
2407                                    TnyStream *stream, 
2408                                    GError *err, 
2409                                    gpointer user_data)
2410 {
2411         DecodeAsyncHelper *helper = (DecodeAsyncHelper *) user_data;
2412
2413         if (helper->banner_idle_id > 0) {
2414                 g_source_remove (helper->banner_idle_id);
2415                 helper->banner_idle_id = 0;
2416         }
2417         if (helper->banner) {
2418                 gtk_widget_destroy (helper->banner);
2419                 helper->banner = NULL;
2420         }
2421         if (cancelled || err) {
2422                 modest_platform_information_banner (NULL, NULL, 
2423                                                     _("mail_ib_file_operation_failed"));
2424                 goto free;
2425         }
2426
2427         /* make the file read-only */
2428         g_chmod(helper->filepath, 0444);
2429
2430         /* Activate the file */
2431         modest_platform_activate_file (helper->filepath, tny_mime_part_get_content_type (mime_part));
2432
2433  free:
2434         /* Frees */
2435         g_free (helper->filepath);
2436         g_slice_free (DecodeAsyncHelper, helper);
2437 }
2438
2439 void
2440 modest_msg_view_window_view_attachment (ModestMsgViewWindow *window, 
2441                                         TnyMimePart *mime_part)
2442 {
2443         ModestMsgViewWindowPrivate *priv;
2444         const gchar *msg_uid;
2445         gchar *attachment_uid = NULL;
2446         gint attachment_index = 0;
2447         TnyList *attachments;
2448
2449         g_return_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window));
2450         g_return_if_fail (TNY_IS_MIME_PART (mime_part) || (mime_part == NULL));
2451         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
2452
2453         msg_uid = modest_msg_view_window_get_message_uid (MODEST_MSG_VIEW_WINDOW (window));
2454         attachments = modest_msg_view_get_attachments (MODEST_MSG_VIEW (priv->msg_view));
2455         attachment_index = modest_list_index (attachments, (GObject *) mime_part);
2456         g_object_unref (attachments);
2457         
2458         if (msg_uid && attachment_index >= 0) {
2459                 attachment_uid = g_strdup_printf ("%s/%d", msg_uid, attachment_index);
2460         }
2461
2462         if (mime_part == NULL) {
2463                 gboolean error = FALSE;
2464                 TnyList *selected_attachments = modest_msg_view_get_selected_attachments (MODEST_MSG_VIEW (priv->msg_view));
2465                 if (selected_attachments == NULL || tny_list_get_length (selected_attachments) == 0) {
2466                         error = TRUE;
2467                 } else if (tny_list_get_length (selected_attachments) > 1) {
2468                         hildon_banner_show_information (NULL, NULL, _("mcen_ib_unable_to_display_more"));
2469                         error = TRUE;
2470                 } else {
2471                         TnyIterator *iter;
2472                         iter = tny_list_create_iterator (selected_attachments);
2473                         mime_part = (TnyMimePart *) tny_iterator_get_current (iter);
2474                         g_object_unref (iter);
2475                 }
2476                 g_object_unref (selected_attachments);
2477
2478                 if (error)
2479                         return;
2480         } else {
2481                 g_object_ref (mime_part);
2482         }
2483
2484         if (tny_mime_part_is_purged (mime_part)) {
2485                 g_object_unref (mime_part);
2486                 return;
2487         }
2488
2489         if (!modest_tny_mime_part_is_msg (mime_part)) {
2490                 gchar *filepath = NULL;
2491                 const gchar *att_filename = tny_mime_part_get_filename (mime_part);
2492                 gboolean show_error_banner = FALSE;
2493                 TnyFsStream *temp_stream = NULL;
2494                 temp_stream = modest_utils_create_temp_stream (att_filename, attachment_uid,
2495                                                                &filepath);
2496                 
2497                 if (temp_stream != NULL) {
2498                         DecodeAsyncHelper *helper = g_slice_new (DecodeAsyncHelper);
2499                         helper->filepath = g_strdup (filepath);
2500                         helper->banner = NULL;
2501                         helper->banner_idle_id = g_timeout_add (1000, decode_async_banner_idle, helper);
2502                         tny_mime_part_decode_to_stream_async (mime_part, TNY_STREAM (temp_stream), 
2503                                                               on_decode_to_stream_async_handler, 
2504                                                               NULL, 
2505                                                               helper);
2506                         g_object_unref (temp_stream);
2507                         /* NOTE: files in the temporary area will be automatically
2508                          * cleaned after some time if they are no longer in use */
2509                 } else {
2510                         if (filepath) {
2511                                 const gchar *content_type;
2512                                 /* the file may already exist but it isn't writable,
2513                                  * let's try to open it anyway */
2514                                 content_type = tny_mime_part_get_content_type (mime_part);
2515                                 modest_platform_activate_file (filepath, content_type);
2516                         } else {
2517                                 g_warning ("%s: modest_utils_create_temp_stream failed", __FUNCTION__);
2518                                 show_error_banner = TRUE;
2519                         }
2520                 }
2521                 if (filepath)
2522                         g_free (filepath);
2523                 if (show_error_banner)
2524                         modest_platform_information_banner (NULL, NULL, _("mail_ib_file_operation_failed"));
2525         } else {
2526                 /* message attachment */
2527                 TnyHeader *header = NULL;
2528                 ModestWindowMgr *mgr;
2529                 ModestWindow *msg_win = NULL;
2530                 gboolean found;
2531
2532                 header = tny_msg_get_header (TNY_MSG (mime_part));
2533                 mgr = modest_runtime_get_window_mgr ();
2534                 found = modest_window_mgr_find_registered_header (mgr, header, &msg_win);
2535
2536                 if (found) {
2537                         /* if it's found, but there is no msg_win, it's probably in the process of being created;
2538                          * thus, we don't do anything */
2539                         g_warning ("window for is already being created");
2540                 } else {
2541                         /* it's not found, so create a new window for it */
2542                         modest_window_mgr_register_header (mgr, header, attachment_uid); /* register the uid before building the window */
2543                         gchar *account = g_strdup (modest_window_get_active_account (MODEST_WINDOW (window)));
2544                         if (!account)
2545                                 account = modest_account_mgr_get_default_account (modest_runtime_get_account_mgr ());
2546                         msg_win = modest_msg_view_window_new_for_attachment (TNY_MSG (mime_part), account, attachment_uid);
2547                         modest_window_set_zoom (MODEST_WINDOW (msg_win),
2548                                                 modest_window_get_zoom (MODEST_WINDOW (window)));
2549                         modest_window_mgr_register_window (mgr, msg_win, MODEST_WINDOW (window));
2550                         gtk_widget_show_all (GTK_WIDGET (msg_win));
2551                 }
2552         }
2553         g_object_unref (mime_part);
2554 }
2555
2556 typedef struct
2557 {
2558         gchar *filename;
2559         TnyMimePart *part;
2560 } SaveMimePartPair;
2561
2562 typedef struct
2563 {
2564         GList *pairs;
2565         GtkWidget *banner;
2566         GnomeVFSResult result;
2567 } SaveMimePartInfo;
2568
2569 static void save_mime_part_info_free (SaveMimePartInfo *info, gboolean with_struct);
2570 static gboolean idle_save_mime_part_show_result (SaveMimePartInfo *info);
2571 static gpointer save_mime_part_to_file (SaveMimePartInfo *info);
2572 static void save_mime_parts_to_file_with_checks (SaveMimePartInfo *info);
2573
2574 static void 
2575 save_mime_part_info_free (SaveMimePartInfo *info, gboolean with_struct)
2576 {
2577         
2578         GList *node;
2579         for (node = info->pairs; node != NULL; node = g_list_next (node)) {
2580                 SaveMimePartPair *pair = (SaveMimePartPair *) node->data;
2581                 g_free (pair->filename);
2582                 g_object_unref (pair->part);
2583                 g_slice_free (SaveMimePartPair, pair);
2584         }
2585         g_list_free (info->pairs);
2586         info->pairs = NULL;
2587         if (with_struct) {
2588                 gtk_widget_destroy (info->banner);
2589                 g_slice_free (SaveMimePartInfo, info);
2590         }
2591 }
2592
2593 static gboolean
2594 idle_save_mime_part_show_result (SaveMimePartInfo *info)
2595 {
2596         if (info->pairs != NULL) {
2597                 save_mime_part_to_file (info);
2598         } else {
2599                 /* This is a GDK lock because we are an idle callback and
2600                  * hildon_banner_show_information is or does Gtk+ code */
2601
2602                 gdk_threads_enter (); /* CHECKED */
2603                 save_mime_part_info_free (info, TRUE);
2604                 if (info->result == GNOME_VFS_OK) {
2605                         hildon_banner_show_information (NULL, NULL, _CS("sfil_ib_saved"));
2606                 } else if (info->result == GNOME_VFS_ERROR_NO_SPACE) {
2607                         hildon_banner_show_information (NULL, NULL, dgettext("ke-recv", 
2608                                                                              "cerm_device_memory_full"));
2609                 } else {
2610                         hildon_banner_show_information (NULL, NULL, _("mail_ib_file_operation_failed"));
2611                 }
2612                 gdk_threads_leave (); /* CHECKED */
2613         }
2614
2615         return FALSE;
2616 }
2617
2618 static gpointer
2619 save_mime_part_to_file (SaveMimePartInfo *info)
2620 {
2621         GnomeVFSHandle *handle;
2622         TnyStream *stream;
2623         SaveMimePartPair *pair = (SaveMimePartPair *) info->pairs->data;
2624
2625         info->result = gnome_vfs_create (&handle, pair->filename, GNOME_VFS_OPEN_WRITE, FALSE, 0644);
2626         if (info->result == GNOME_VFS_OK) {
2627                 GError *error = NULL;
2628                 stream = tny_vfs_stream_new (handle);
2629                 if (tny_mime_part_decode_to_stream (pair->part, stream, &error) < 0) {
2630                         g_warning ("modest: could not save attachment %s: %d (%s)\n", pair->filename, error?error->code:-1, error?error->message:"Unknown error");
2631                         
2632                         info->result = GNOME_VFS_ERROR_IO;
2633                 }
2634                 g_object_unref (G_OBJECT (stream));
2635                 g_object_unref (pair->part);
2636                 g_slice_free (SaveMimePartPair, pair);
2637                 info->pairs = g_list_delete_link (info->pairs, info->pairs);
2638         } else {
2639                 g_warning ("modest: could not create save attachment %s: %s\n", pair->filename, gnome_vfs_result_to_string (info->result));
2640                 save_mime_part_info_free (info, FALSE);
2641         }
2642
2643         g_idle_add ((GSourceFunc) idle_save_mime_part_show_result, info);
2644         return NULL;
2645 }
2646
2647 static void
2648 save_mime_parts_to_file_with_checks (SaveMimePartInfo *info)
2649 {
2650         gboolean is_ok = TRUE;
2651         gint replaced_files = 0;
2652         const GList *files = info->pairs;
2653         const GList *iter;
2654
2655         for (iter = files; (iter != NULL) && (replaced_files < 2); iter = g_list_next(iter)) {
2656                 SaveMimePartPair *pair = iter->data;
2657                 if (modest_utils_file_exists (pair->filename)) {
2658                         replaced_files++;
2659                 }
2660         }
2661         if (replaced_files) {
2662                 GtkWidget *confirm_overwrite_dialog;
2663                 const gchar *message = (replaced_files == 1) ?
2664                         _FM("docm_nc_replace_file") : _FM("docm_nc_replace_multiple");
2665                 confirm_overwrite_dialog = hildon_note_new_confirmation (NULL, message);
2666                 if (gtk_dialog_run (GTK_DIALOG (confirm_overwrite_dialog)) != GTK_RESPONSE_OK) {
2667                         is_ok = FALSE;
2668                 }
2669                 gtk_widget_destroy (confirm_overwrite_dialog);
2670         }
2671
2672         if (!is_ok) {
2673                 save_mime_part_info_free (info, TRUE);
2674         } else {
2675                 GtkWidget *banner = hildon_banner_show_animation (NULL, NULL, 
2676                                                                   _CS("sfil_ib_saving"));
2677                 info->banner = banner;
2678                 g_thread_create ((GThreadFunc)save_mime_part_to_file, info, FALSE, NULL);
2679         }
2680
2681 }
2682
2683 static void
2684 save_attachments_response (GtkDialog *dialog,
2685                            gint       arg1,
2686                            gpointer   user_data)  
2687 {
2688         TnyList *mime_parts;
2689         gchar *chooser_uri;
2690         GList *files_to_save = NULL;
2691
2692         mime_parts = TNY_LIST (user_data);
2693
2694         if (arg1 != GTK_RESPONSE_OK)
2695                 goto end;
2696
2697         chooser_uri = gtk_file_chooser_get_uri (GTK_FILE_CHOOSER (dialog));
2698
2699         if (!modest_utils_folder_writable (chooser_uri)) {
2700                 hildon_banner_show_information 
2701                         (NULL, NULL, dgettext("hildon-fm", "sfil_ib_readonly_location"));
2702         } else {
2703                 TnyIterator *iter;
2704
2705                 iter = tny_list_create_iterator (mime_parts);
2706                 while (!tny_iterator_is_done (iter)) {
2707                         TnyMimePart *mime_part = (TnyMimePart *) tny_iterator_get_current (iter);
2708
2709                         if ((modest_tny_mime_part_is_attachment_for_modest (mime_part)) &&
2710                             !tny_mime_part_is_purged (mime_part) &&
2711                             (tny_mime_part_get_filename (mime_part) != NULL)) {
2712                                 SaveMimePartPair *pair;
2713                                         
2714                                 pair = g_slice_new0 (SaveMimePartPair);
2715
2716                                 if (tny_list_get_length (mime_parts) > 1) {
2717                                         gchar *escaped = 
2718                                                 gnome_vfs_escape_slashes (tny_mime_part_get_filename (mime_part));
2719                                         pair->filename = g_build_filename (chooser_uri, escaped, NULL);
2720                                         g_free (escaped);
2721                                 } else {
2722                                         pair->filename = g_strdup (chooser_uri);
2723                                 }
2724                                 pair->part = mime_part;
2725                                 files_to_save = g_list_prepend (files_to_save, pair);
2726                         }
2727                         tny_iterator_next (iter);
2728                 }
2729                 g_object_unref (iter);
2730         }
2731         g_free (chooser_uri);
2732
2733         if (files_to_save != NULL) {
2734                 SaveMimePartInfo *info = g_slice_new0 (SaveMimePartInfo);
2735                 info->pairs = files_to_save;
2736                 info->result = TRUE;
2737                 save_mime_parts_to_file_with_checks (info);
2738         }
2739
2740  end:
2741         /* Free and close the dialog */
2742         g_object_unref (mime_parts);
2743         gtk_widget_destroy (GTK_WIDGET (dialog));
2744 }
2745
2746 void
2747 modest_msg_view_window_save_attachments (ModestMsgViewWindow *window, TnyList *mime_parts)
2748 {
2749         ModestMsgViewWindowPrivate *priv;
2750         GtkWidget *save_dialog = NULL;
2751         gchar *folder = NULL;
2752         gchar *filename = NULL;
2753         gchar *save_multiple_str = NULL;
2754
2755         g_return_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window));
2756         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
2757
2758         if (mime_parts == NULL) {
2759                 mime_parts = modest_msg_view_get_selected_attachments (MODEST_MSG_VIEW (priv->msg_view));
2760                 if (mime_parts == NULL || tny_list_get_length (mime_parts) == 0)
2761                         return;
2762         } else {
2763                 g_object_ref (mime_parts);
2764         }
2765
2766         /* prepare dialog */
2767         if (tny_list_get_length (mime_parts) == 1) {
2768                 TnyIterator *iter;
2769                 /* only one attachment selected */
2770                 iter = tny_list_create_iterator (mime_parts);
2771                 TnyMimePart *mime_part = (TnyMimePart *) tny_iterator_get_current (iter);
2772                 g_object_unref (iter);
2773                 if (!modest_tny_mime_part_is_msg (mime_part) && 
2774                     modest_tny_mime_part_is_attachment_for_modest (mime_part) &&
2775                     !tny_mime_part_is_purged (mime_part)) {
2776                         filename = g_strdup (tny_mime_part_get_filename (mime_part));
2777                 } else {
2778                         /* TODO: show any error? */
2779                         g_warning ("Tried to save a non-file attachment");
2780                         g_object_unref (mime_parts);
2781                         return;
2782                 }
2783                 g_object_unref (mime_part);
2784         } else {
2785                 save_multiple_str = g_strdup_printf (_FM("sfil_va_number_of_objects_attachments"), 
2786                                                      tny_list_get_length (mime_parts));
2787         }
2788         
2789         save_dialog = hildon_file_chooser_dialog_new (GTK_WINDOW (window), 
2790                                                       GTK_FILE_CHOOSER_ACTION_SAVE);
2791
2792         /* set folder */
2793         folder = g_build_filename (g_getenv (MYDOCS_ENV), DOCS_FOLDER, NULL);
2794         gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (save_dialog), folder);
2795         g_free (folder);
2796
2797         /* set filename */
2798         if (filename) {
2799                 gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (save_dialog), 
2800                                                    filename);
2801                 g_free (filename);
2802         }
2803
2804         /* if multiple, set multiple string */
2805         if (save_multiple_str) {
2806                 g_object_set (G_OBJECT (save_dialog), "save-multiple", save_multiple_str, NULL);
2807                 gtk_window_set_title (GTK_WINDOW (save_dialog), _FM("sfil_ti_save_objects_files"));
2808         }
2809
2810         /* We must run this asynchronously, because the hildon dialog
2811            performs a gtk_dialog_run by itself which leads to gdk
2812            deadlocks */
2813         g_signal_connect (save_dialog, "response", 
2814                           G_CALLBACK (save_attachments_response), mime_parts);
2815
2816         gtk_widget_show_all (save_dialog);
2817 }
2818
2819 static gboolean
2820 show_remove_attachment_information (gpointer userdata)
2821 {
2822         ModestMsgViewWindow *window = (ModestMsgViewWindow *) userdata;
2823         ModestMsgViewWindowPrivate *priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
2824
2825         /* We're outside the main lock */
2826         gdk_threads_enter ();
2827
2828         if (priv->remove_attachment_banner != NULL) {
2829                 gtk_widget_destroy (priv->remove_attachment_banner);
2830                 g_object_unref (priv->remove_attachment_banner);
2831         }
2832
2833         priv->remove_attachment_banner = g_object_ref (
2834                 hildon_banner_show_animation (NULL, NULL, _("mcen_me_inbox_remove_attachments")));
2835
2836         gdk_threads_leave ();
2837
2838         return FALSE;
2839 }
2840
2841 void
2842 modest_msg_view_window_remove_attachments (ModestMsgViewWindow *window, gboolean get_all)
2843 {
2844         ModestMsgViewWindowPrivate *priv;
2845         TnyList *mime_parts = NULL;
2846         gchar *confirmation_message;
2847         gint response;
2848         gint n_attachments;
2849         TnyMsg *msg;
2850         TnyIterator *iter;
2851
2852         g_return_if_fail (MODEST_IS_MSG_VIEW_WINDOW (window));
2853         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
2854
2855         if (get_all)
2856                 mime_parts = modest_msg_view_get_attachments (MODEST_MSG_VIEW (priv->msg_view));
2857         else
2858                 mime_parts = modest_msg_view_get_selected_attachments (MODEST_MSG_VIEW (priv->msg_view));
2859                 
2860         /* Remove already purged messages from mime parts list */
2861         iter = tny_list_create_iterator (mime_parts);
2862         while (!tny_iterator_is_done (iter)) {
2863                 TnyMimePart *part = TNY_MIME_PART (tny_iterator_get_current (iter));
2864                 tny_iterator_next (iter);
2865                 if (tny_mime_part_is_purged (part)) {
2866                         tny_list_remove (mime_parts, (GObject *) part);
2867                 }
2868                 g_object_unref (part);
2869         }
2870         g_object_unref (iter);
2871
2872         if (tny_list_get_length (mime_parts) == 0) {
2873                 g_object_unref (mime_parts);
2874                 return;
2875         }
2876
2877         n_attachments = tny_list_get_length (mime_parts);
2878         if (n_attachments == 1) {
2879                 gchar *filename;
2880                 TnyMimePart *part;
2881
2882                 iter = tny_list_create_iterator (mime_parts);
2883                 part = (TnyMimePart *) tny_iterator_get_current (iter);
2884                 g_object_unref (iter);
2885                 if (modest_tny_mime_part_is_msg (part)) {
2886                         TnyHeader *header;
2887                         header = tny_msg_get_header (TNY_MSG (part));
2888                         filename = tny_header_dup_subject (header);
2889                         g_object_unref (header);
2890                         if (filename == NULL)
2891                                 filename = g_strdup (_("mail_va_no_subject"));
2892                 } else {
2893                         filename = g_strdup (tny_mime_part_get_filename (TNY_MIME_PART (part)));
2894                 }
2895                 confirmation_message = g_strdup_printf (_("mcen_nc_purge_file_text"), filename);
2896                 g_free (filename);
2897                 g_object_unref (part);
2898         } else {
2899                 confirmation_message = g_strdup_printf (ngettext("mcen_nc_purge_file_text", 
2900                                                                  "mcen_nc_purge_files_text", 
2901                                                                  n_attachments), n_attachments);
2902         }
2903         response = modest_platform_run_confirmation_dialog (GTK_WINDOW (window),
2904                                                             confirmation_message);
2905         g_free (confirmation_message);
2906
2907         if (response != GTK_RESPONSE_OK) {
2908                 g_object_unref (mime_parts);
2909                 return;
2910         }
2911
2912         priv->purge_timeout = g_timeout_add (2000, show_remove_attachment_information, window);
2913         
2914         iter = tny_list_create_iterator (mime_parts);
2915         while (!tny_iterator_is_done (iter)) {
2916                 TnyMimePart *part;
2917
2918                 part = (TnyMimePart *) tny_iterator_get_current (iter);
2919                 tny_mime_part_set_purged (TNY_MIME_PART (part));
2920                 g_object_unref (part);
2921                 tny_iterator_next (iter);
2922         }
2923         g_object_unref (iter);
2924
2925         msg = tny_msg_view_get_msg (TNY_MSG_VIEW (priv->msg_view));
2926         tny_msg_view_clear (TNY_MSG_VIEW (priv->msg_view));
2927         tny_msg_rewrite_cache (msg);
2928         tny_msg_view_set_msg (TNY_MSG_VIEW (priv->msg_view), msg);
2929         g_object_unref (msg);
2930
2931         g_object_unref (mime_parts);
2932
2933         if (priv->purge_timeout > 0) {
2934                 g_source_remove (priv->purge_timeout);
2935                 priv->purge_timeout = 0;
2936         }
2937
2938         if (priv->remove_attachment_banner) {
2939                 gtk_widget_destroy (priv->remove_attachment_banner);
2940                 g_object_unref (priv->remove_attachment_banner);
2941                 priv->remove_attachment_banner = NULL;
2942         }
2943
2944
2945 }
2946
2947
2948 static void
2949 update_window_title (ModestMsgViewWindow *window)
2950 {
2951         ModestMsgViewWindowPrivate *priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
2952         TnyMsg *msg = NULL;
2953         TnyHeader *header = NULL;
2954         gchar *subject = NULL;
2955         
2956         msg = tny_msg_view_get_msg (TNY_MSG_VIEW (priv->msg_view));
2957
2958         if (msg != NULL) {
2959                 header = tny_msg_get_header (msg);
2960                 subject = tny_header_dup_subject (header);
2961                 g_object_unref (header);
2962                 g_object_unref (msg);
2963         }
2964
2965         if ((subject == NULL)||(subject[0] == '\0')) {
2966                 g_free (subject);
2967                 subject = g_strdup (_("mail_va_no_subject"));
2968         }
2969
2970         gtk_window_set_title (GTK_WINDOW (window), subject);
2971 }
2972
2973
2974 static void on_move_focus (GtkWidget *widget,
2975                            GtkDirectionType direction,
2976                            gpointer userdata)
2977 {
2978         g_signal_stop_emission_by_name (G_OBJECT (widget), "move-focus");
2979 }
2980
2981 static TnyStream *
2982 fetch_image_open_stream (TnyStreamCache *self, gint64 *expected_size, gchar *uri)
2983 {
2984         GnomeVFSResult result;
2985         GnomeVFSHandle *handle = NULL;
2986         GnomeVFSFileInfo *info = NULL;
2987         TnyStream *stream;
2988
2989         result = gnome_vfs_open (&handle, uri, GNOME_VFS_OPEN_READ);
2990         if (result != GNOME_VFS_OK) {
2991                 *expected_size = 0;
2992                 return NULL;
2993         }
2994         
2995         info = gnome_vfs_file_info_new ();
2996         result = gnome_vfs_get_file_info_from_handle (handle, info, GNOME_VFS_FILE_INFO_DEFAULT);
2997         if (result != GNOME_VFS_OK || ! (info->valid_fields & GNOME_VFS_FILE_INFO_FIELDS_SIZE)) {
2998                 /* We put a "safe" default size for going to cache */
2999                 *expected_size = (300*1024);
3000         } else {
3001                 *expected_size = info->size;
3002         }
3003         gnome_vfs_file_info_unref (info);
3004
3005         stream = tny_vfs_stream_new (handle);
3006
3007         return stream;
3008
3009 }
3010
3011 typedef struct {
3012         gchar *uri;
3013         gchar *cache_id;
3014         TnyStream *output_stream;
3015         GtkWidget *msg_view;
3016 } FetchImageData;
3017
3018 gboolean
3019 on_fetch_image_idle_refresh_view (gpointer userdata)
3020 {
3021
3022         FetchImageData *fidata = (FetchImageData *) userdata;
3023         g_message ("REFRESH VIEW");
3024         if (GTK_WIDGET_DRAWABLE (fidata->msg_view)) {
3025                 g_message ("QUEUING DRAW");
3026                 gtk_widget_queue_draw (fidata->msg_view);
3027         }
3028         g_object_unref (fidata->msg_view);
3029         g_slice_free (FetchImageData, fidata);
3030         return FALSE;
3031 }
3032
3033 static gpointer
3034 on_fetch_image_thread (gpointer userdata)
3035 {
3036         FetchImageData *fidata = (FetchImageData *) userdata;
3037         TnyStreamCache *cache;
3038         TnyStream *cache_stream;
3039
3040         cache = modest_runtime_get_images_cache ();
3041         cache_stream = tny_stream_cache_get_stream (cache, fidata->cache_id, (TnyStreamCacheOpenStreamFetcher) fetch_image_open_stream, (gpointer) fidata->uri);
3042         g_free (fidata->cache_id);
3043         g_free (fidata->uri);
3044
3045         if (cache_stream != NULL) {
3046                 tny_stream_write_to_stream (cache_stream, fidata->output_stream);
3047                 tny_stream_close (cache_stream);
3048                 g_object_unref (cache_stream);
3049         }
3050
3051         tny_stream_close (fidata->output_stream);
3052         g_object_unref (fidata->output_stream);
3053
3054
3055         gdk_threads_enter ();
3056         g_idle_add (on_fetch_image_idle_refresh_view, fidata);
3057         gdk_threads_leave ();
3058
3059         return NULL;
3060 }
3061
3062 static gboolean
3063 on_fetch_image (ModestMsgView *msgview,
3064                 const gchar *uri,
3065                 TnyStream *stream,
3066                 ModestMsgViewWindow *window)
3067 {
3068         const gchar *current_account;
3069         ModestMsgViewWindowPrivate *priv;
3070         FetchImageData *fidata;
3071
3072         priv = MODEST_MSG_VIEW_WINDOW_GET_PRIVATE (window);
3073
3074         current_account = modest_window_get_active_account (MODEST_WINDOW (window));
3075
3076         fidata = g_slice_new0 (FetchImageData);
3077         fidata->msg_view = g_object_ref (msgview);
3078         fidata->uri = g_strdup (uri);
3079         fidata->cache_id = modest_images_cache_get_id (current_account, uri);
3080         fidata->output_stream = g_object_ref (stream);
3081
3082         if (g_thread_create (on_fetch_image_thread, fidata, FALSE, NULL) == NULL) {
3083                 g_object_unref (fidata->output_stream);
3084                 g_free (fidata->cache_id);
3085                 g_free (fidata->uri);
3086                 g_object_unref (fidata->msg_view);
3087                 g_slice_free (FetchImageData, fidata);
3088                 tny_stream_close (stream);
3089                 return FALSE;
3090         }
3091
3092         return TRUE;;
3093 }
3094
3095 static void 
3096 setup_menu (ModestMsgViewWindow *self)
3097 {
3098         g_return_if_fail (MODEST_IS_MSG_VIEW_WINDOW(self));
3099
3100         /* Settings menu buttons */
3101         modest_hildon2_window_add_to_menu (MODEST_HILDON2_WINDOW (self), _("mcen_me_inbox_replytoall"), NULL,
3102                                            APP_MENU_CALLBACK (modest_ui_actions_on_reply_all),
3103                                            MODEST_DIMMING_CALLBACK (modest_ui_dimming_rules_on_reply_msg));
3104         modest_hildon2_window_add_to_menu (MODEST_HILDON2_WINDOW (self), _("mcen_me_inbox_forward"), "<Control>d",
3105                                            APP_MENU_CALLBACK (modest_ui_actions_on_forward),
3106                                            MODEST_DIMMING_CALLBACK (modest_ui_dimming_rules_on_reply_msg));
3107         
3108         modest_hildon2_window_add_to_menu (MODEST_HILDON2_WINDOW (self), _("mcen_me_inbox_mark_as_read"), NULL,
3109                                            APP_MENU_CALLBACK (modest_ui_actions_on_mark_as_read),
3110                                            MODEST_DIMMING_CALLBACK (modest_ui_dimming_rules_on_mark_as_read_msg_in_view));
3111         modest_hildon2_window_add_to_menu (MODEST_HILDON2_WINDOW (self), _("mcen_me_inbox_mark_as_unread"), NULL,
3112                                            APP_MENU_CALLBACK (modest_ui_actions_on_mark_as_unread),
3113                                            MODEST_DIMMING_CALLBACK (modest_ui_dimming_rules_on_mark_as_unread_msg_in_view));
3114         
3115         modest_hildon2_window_add_to_menu (MODEST_HILDON2_WINDOW (self), _("mcen_me_viewer_save_attachments"), NULL,
3116                                            APP_MENU_CALLBACK (modest_ui_actions_save_attachments),
3117                                            MODEST_DIMMING_CALLBACK (modest_ui_dimming_rules_on_save_attachments));
3118         modest_hildon2_window_add_to_menu (MODEST_HILDON2_WINDOW (self), _("mcen_me_inbox_remove_attachments"), NULL,
3119                                            APP_MENU_CALLBACK (modest_ui_actions_remove_attachments),
3120                                            MODEST_DIMMING_CALLBACK (modest_ui_dimming_rules_on_remove_attachments));
3121         
3122         modest_hildon2_window_add_to_menu (MODEST_HILDON2_WINDOW (self), _("mcen_me_new_message"), "<Control>n",
3123                                            APP_MENU_CALLBACK (modest_ui_actions_on_new_msg),
3124                                            MODEST_DIMMING_CALLBACK (modest_ui_dimming_rules_on_new_msg));
3125         modest_hildon2_window_add_to_menu (MODEST_HILDON2_WINDOW (self), _("mcen_me_viewer_addtocontacts"), NULL,
3126                                            APP_MENU_CALLBACK (modest_ui_actions_add_to_contacts),
3127                                            MODEST_DIMMING_CALLBACK (modest_ui_dimming_rules_on_add_to_contacts));
3128 }