99fc120b223fcb56fb5c9db270603d20ce26004b
[modest] / src / modest-utils.c
1 /* Copyright (c) 2007, Nokia Corporation
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  * * Redistributions of source code must retain the above copyright
9  *   notice, this list of conditions and the following disclaimer.
10  * * Redistributions in binary form must reproduce the above copyright
11  *   notice, this list of conditions and the following disclaimer in the
12  *   documentation and/or other materials provided with the distribution.
13  * * Neither the name of the Nokia Corporation nor the names of its
14  *   contributors may be used to endorse or promote products derived from
15  *   this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
18  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include <glib.h>
31 #include <glib/gstdio.h>
32 #include <errno.h>
33 #include <string.h> /* for strlen */
34 #include <modest-runtime.h>
35 #include <libgnomevfs/gnome-vfs.h>
36 #include <tny-fs-stream.h>
37 #include <tny-camel-account.h>
38 #include <tny-status.h>
39 #include <tny-camel-transport-account.h>
40 #include <tny-camel-imap-store-account.h>
41 #include <tny-camel-pop-store-account.h>
42
43 #include <modest-defs.h>
44 #include "modest-utils.h"
45 #include "modest-platform.h"
46 #include <modest-account-protocol.h>
47 #include "modest-account-mgr-helpers.h"
48 #include "modest-text-utils.h"
49 #include <modest-local-folder-info.h>
50 #include "widgets/modest-header-view.h"
51 #include "widgets/modest-main-window.h"
52 #include "modest-widget-memory.h"
53 #include "widgets/modest-sort-criterium-view.h"
54 #ifdef MODEST_TOOLKIT_HILDON2
55 #include "modest-header-window.h"
56 #endif
57
58 GQuark
59 modest_utils_get_supported_secure_authentication_error_quark (void)
60 {
61         return g_quark_from_static_string("modest-utils-get-supported-secure-authentication-error-quark");
62 }
63
64 gboolean
65 modest_utils_folder_writable (const gchar *filename)
66 {
67         g_return_val_if_fail (filename, FALSE);
68
69         if (!filename)
70                 return FALSE;
71
72         if (g_strncasecmp (filename, "obex", 4) != 0) {
73                 GnomeVFSFileInfo *folder_info = NULL;
74                 GnomeVFSResult result = GNOME_VFS_OK;
75                 GnomeVFSURI *uri = NULL;
76                 GnomeVFSURI *folder_uri = NULL;
77
78                 uri = gnome_vfs_uri_new (filename);
79                 folder_uri = gnome_vfs_uri_get_parent (uri);
80
81                 if (folder_uri != NULL) {
82                         folder_info = gnome_vfs_file_info_new ();
83                         result = gnome_vfs_get_file_info_uri (folder_uri, folder_info,
84                                                               GNOME_VFS_FILE_INFO_GET_ACCESS_RIGHTS);
85                         gnome_vfs_uri_unref (folder_uri);
86                 }
87                 gnome_vfs_uri_unref (uri);
88
89                 if (folder_uri == NULL)
90                         return FALSE;
91
92                 if ((result != GNOME_VFS_OK) ||
93                     (!((folder_info->permissions & GNOME_VFS_PERM_ACCESS_WRITABLE) ||
94                        (folder_info->permissions & GNOME_VFS_PERM_USER_WRITE)))) {
95
96                         gnome_vfs_file_info_unref (folder_info);
97                         return FALSE;
98                 }
99                 gnome_vfs_file_info_unref (folder_info);
100         }
101         return TRUE;
102 }
103
104 gboolean
105 modest_utils_file_exists (const gchar *filename)
106 {
107         GnomeVFSURI *uri = NULL;
108         gboolean result = FALSE;
109
110         g_return_val_if_fail (filename, FALSE);
111
112         uri = gnome_vfs_uri_new (filename);
113         if (uri) {
114                 result = gnome_vfs_uri_exists (uri);
115                 gnome_vfs_uri_unref (uri);
116         }
117         return result;
118 }
119
120 TnyFsStream *
121 modest_utils_create_temp_stream (const gchar *orig_name, const gchar *hash_base, gchar **path)
122 {
123         gint fd;
124         gchar *filepath = NULL;
125         gchar *tmpdir;
126         guint hash_number;
127
128         /* hmmm... maybe we need a modest_text_utils_validate_file_name? */
129         g_return_val_if_fail (orig_name && strlen(orig_name) != 0, NULL);
130
131         if (strlen(orig_name) > 200) {
132                 g_warning ("%s: filename too long ('%s')",
133                            __FUNCTION__, orig_name);
134                 return NULL;
135         }
136
137         if (g_strstr_len (orig_name, strlen(orig_name), "/") != NULL) {
138                 g_warning ("%s: filename contains '/' character(s) (%s)",
139                            __FUNCTION__, orig_name);
140                 return NULL;
141         }
142
143         /* make a random subdir under /tmp or /var/tmp */
144         if (hash_base != NULL) {
145                 hash_number = g_str_hash (hash_base);
146         } else {
147                 hash_number = (guint) random ();
148         }
149         tmpdir = g_strdup_printf ("%s/%u", g_get_tmp_dir (), hash_number);
150         if ((g_access (tmpdir, R_OK) == -1) && (g_mkdir (tmpdir, 0755) == -1)) {
151                 g_warning ("%s: failed to create dir '%s': %s",
152                            __FUNCTION__, tmpdir, g_strerror(errno));
153                 g_free (tmpdir);
154                 return NULL;
155         }
156
157         filepath = g_strconcat (tmpdir, "/", orig_name, NULL);
158
159         /* if file exists, first we try to remove it */
160         if (modest_utils_file_exists (filepath)) {
161                 g_unlink (filepath);
162         }
163
164         /* don't overwrite if it already exists, even if it is writable */
165         if (modest_utils_file_exists (filepath)) {
166                 if (path!=NULL) {
167                         *path = filepath;
168                 } else {
169                         g_free (filepath);
170                 }
171                 g_free (tmpdir);
172                 return NULL;
173         } else {
174                 /* try to write the file there */
175                 fd = g_open (filepath, O_CREAT|O_WRONLY|O_TRUNC, 0644);
176                 if (fd == -1) {
177                         g_warning ("%s: failed to create '%s': %s",
178                                         __FUNCTION__, filepath, g_strerror(errno));
179                         g_free (filepath);
180                         g_free (tmpdir);
181                         return NULL;
182                 }
183         }
184
185         g_free (tmpdir);
186
187         if (path)
188                 *path = filepath;
189         else
190                 g_free (filepath);
191
192         return TNY_FS_STREAM (tny_fs_stream_new (fd));
193 }
194
195 typedef struct 
196 {
197         GList **result;
198         GtkWidget* dialog;
199         GtkWidget* progress;
200 } ModestGetSupportedAuthInfo;
201
202 static gboolean
203 on_idle_secure_auth_finished (gpointer user_data)
204 {
205         /* Operation has finished, close the dialog. Control continues after
206          * gtk_dialog_run in modest_utils_get_supported_secure_authentication_methods() */
207         gdk_threads_enter(); /* CHECKED */
208         gtk_dialog_response (GTK_DIALOG (user_data), GTK_RESPONSE_ACCEPT);
209         gdk_threads_leave(); /* CHECKED */
210
211         return FALSE;
212 }
213
214 static void
215 on_camel_account_get_supported_secure_authentication (TnyCamelAccount *self,
216                                                       gboolean cancelled,
217                                                       TnyList *auth_types,
218                                                       GError *err,
219                                                       gpointer user_data)
220 {
221         ModestPairList *pairs;
222         GList *result;
223         ModestProtocolRegistry *protocol_registry;
224         ModestGetSupportedAuthInfo *info = (ModestGetSupportedAuthInfo*)user_data;
225         TnyIterator* iter;
226
227         g_return_if_fail (user_data);
228         g_return_if_fail (TNY_IS_CAMEL_ACCOUNT(self));
229         g_return_if_fail (TNY_IS_LIST(auth_types));
230
231         info = (ModestGetSupportedAuthInfo *) user_data;
232
233         /* Free everything if the actual action was canceled */
234         if (cancelled) {
235                 g_debug ("%s: operation canceled\n", __FUNCTION__);
236                 goto close_dialog;
237         }
238
239         if (err) {
240                 g_debug ("%s: error getting the supported auth methods\n", __FUNCTION__);
241                 goto close_dialog;
242         }
243
244         if (!auth_types) {
245                 g_debug ("%s: auth_types is NULL.\n", __FUNCTION__);
246                 goto close_dialog;
247         }
248
249         if (tny_list_get_length(auth_types) == 0) {
250                 g_debug ("%s: auth_types is an empty TnyList.\n", __FUNCTION__);
251                 goto close_dialog;
252         }
253
254         protocol_registry = modest_runtime_get_protocol_registry ();
255         pairs = modest_protocol_registry_get_pair_list_by_tag (protocol_registry, MODEST_PROTOCOL_REGISTRY_AUTH_PROTOCOLS);
256
257         /* Get the enum value for the strings: */
258         result = NULL;
259         iter = tny_list_create_iterator(auth_types);
260         while (!tny_iterator_is_done(iter)) {
261                 TnyPair *pair;
262                 const gchar *auth_name;
263                 ModestProtocolType protocol_type;
264
265                 pair = TNY_PAIR(tny_iterator_get_current(iter));
266                 auth_name = NULL;
267                 if (pair) {
268                         auth_name = tny_pair_get_name(pair);
269                         g_object_unref (pair);
270                         pair = NULL;
271                 }
272
273                 g_debug ("%s: auth_name=%s\n", __FUNCTION__, auth_name);
274
275                 protocol_type = modest_protocol_get_type_id (modest_protocol_registry_get_protocol_by_name (protocol_registry,
276                                                                                                             MODEST_PROTOCOL_REGISTRY_AUTH_PROTOCOLS,
277                                                                                                             auth_name));
278
279                 if (modest_protocol_registry_protocol_type_is_secure (protocol_registry, protocol_type))
280                         result = g_list_prepend(result, GINT_TO_POINTER(protocol_type));
281
282                 tny_iterator_next(iter);
283         }
284         g_object_unref (iter);
285
286         modest_pair_list_free (pairs);
287         *(info->result) = result;
288
289  close_dialog:
290         /* Close the dialog in a main thread */
291         g_idle_add(on_idle_secure_auth_finished, info->dialog);
292
293         /* Free the info */
294         g_slice_free (ModestGetSupportedAuthInfo, info);
295 }
296
297 typedef struct {
298         GtkWidget *progress;
299         gboolean not_finished;
300 } KeepPulsing;
301
302 static gboolean
303 keep_pulsing (gpointer user_data)
304 {
305         KeepPulsing *info = (KeepPulsing *) user_data;
306
307         if (!info->not_finished) {
308                 g_slice_free (KeepPulsing, info);
309                 return FALSE;
310         }
311
312         gtk_progress_bar_pulse (GTK_PROGRESS_BAR (info->progress));
313         return TRUE;
314 }
315
316 GList*
317 modest_utils_get_supported_secure_authentication_methods (ModestProtocolType protocol_type,
318                                                           const gchar* hostname,
319                                                           gint port,
320                                                           const gchar* username,
321                                                           GtkWindow *parent_window,
322                                                           GError** error)
323 {
324         TnyAccount * tny_account = NULL;
325         ModestProtocolRegistry *protocol_registry;
326         GtkWidget *dialog;
327         gint retval;
328         ModestTnyAccountStore *account_store;
329         TnySessionCamel *session = NULL;
330         ModestProtocol *protocol = NULL;
331         GList *result = NULL;
332         GtkWidget *progress;
333
334         g_return_val_if_fail (protocol_type != MODEST_PROTOCOL_REGISTRY_TYPE_INVALID, NULL);
335
336         protocol_registry = modest_runtime_get_protocol_registry ();
337
338         /* We need a connection to get the capabilities; */
339         if (!modest_platform_connect_and_wait (GTK_WINDOW (parent_window), NULL))
340                 return NULL;
341
342         /* Create a TnyCamelAccount so we can use 
343          * tny_camel_account_get_supported_secure_authentication(): */
344         protocol = modest_protocol_registry_get_protocol_by_type (protocol_registry, protocol_type);
345         tny_account = NULL;
346         if (MODEST_IS_ACCOUNT_PROTOCOL (protocol)) {
347                 tny_account = modest_account_protocol_create_account (MODEST_ACCOUNT_PROTOCOL (protocol));
348         }
349
350         if (!tny_account) {
351                 g_printerr ("%s could not create tny account.", __FUNCTION__);
352                 return NULL;
353         }
354
355         /* Set proto, so that the prepare_func() vfunc will work when
356          * we call set_session(): */
357         protocol = modest_protocol_registry_get_protocol_by_type (protocol_registry, protocol_type);
358         tny_account_set_id (tny_account, "temp_account");
359         tny_account_set_proto (tny_account, modest_protocol_get_name (protocol));
360         tny_account_set_hostname (tny_account, hostname);
361         tny_account_set_user (tny_account, username);
362
363         if(port > 0)
364                 tny_account_set_port (tny_account, port);
365
366         /* Set the session for the account, so we can use it: */
367         account_store = modest_runtime_get_account_store ();
368         session = modest_tny_account_store_get_session (TNY_ACCOUNT_STORE (account_store));
369         g_return_val_if_fail (session, NULL);
370         tny_camel_account_set_session (TNY_CAMEL_ACCOUNT(tny_account), session);
371
372         dialog = gtk_dialog_new_with_buttons(" ",
373                                              parent_window,
374                                              GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
375                                              _("mcen_bd_dialog_cancel"),
376                                              GTK_RESPONSE_REJECT,
377                                              NULL);
378
379         /* Ask camel to ask the server, asynchronously: */
380         ModestGetSupportedAuthInfo *info = g_slice_new (ModestGetSupportedAuthInfo);
381         info->result = &result;
382         info->dialog = dialog;
383
384         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(info->dialog)->vbox),
385                           gtk_label_new(_("emev_ni_checking_supported_auth_methods")));
386         progress = gtk_progress_bar_new();
387         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(info->dialog)->vbox), progress);
388         gtk_widget_show_all(info->dialog);
389
390         KeepPulsing *pi = g_slice_new (KeepPulsing);
391         pi->progress = progress;
392         pi->not_finished = TRUE;
393
394         /* Starts the pulsing of the progressbar */
395         g_timeout_add (500, keep_pulsing, pi);
396
397         tny_camel_account_get_supported_secure_authentication (TNY_CAMEL_ACCOUNT (tny_account),
398                                                                on_camel_account_get_supported_secure_authentication,
399                                                                NULL,
400                                                                info);
401
402         retval = gtk_dialog_run (GTK_DIALOG (info->dialog));
403
404         pi->not_finished = FALSE;
405         /* pi is freed in the timeout itself to avoid a GCond here */
406
407         gtk_widget_destroy(dialog);
408
409         /* Frees */
410         tny_account_cancel (tny_account);
411         g_object_unref (tny_account);
412
413         return result;
414 }
415
416 void
417 modest_utils_show_dialog_and_forget (GtkWindow *parent_window,
418                                      GtkDialog *dialog)
419 {
420         g_return_if_fail (GTK_IS_WINDOW(parent_window));
421         g_return_if_fail (GTK_IS_DIALOG(dialog));
422
423         gtk_window_set_transient_for (GTK_WINDOW (dialog), parent_window);
424
425         /* Destroy the dialog when it is closed: */
426         g_signal_connect_swapped (dialog,
427                                   "response",
428                                   G_CALLBACK (gtk_widget_destroy),
429                                   dialog);
430
431         gtk_widget_show (GTK_WIDGET (dialog));
432 }
433
434 void
435 modest_utils_toggle_action_set_active_block_notify (GtkToggleAction *action, gboolean value)
436 {
437         GSList *proxies = NULL;
438
439         g_return_if_fail (GTK_IS_TOGGLE_ACTION (action));
440
441         for (proxies = gtk_action_get_proxies (GTK_ACTION (action));
442              proxies != NULL; proxies = g_slist_next (proxies)) {
443                 GtkWidget *widget = (GtkWidget *) proxies->data;
444                 gtk_action_block_activate_from (GTK_ACTION (action), widget);
445         }
446
447         gtk_toggle_action_set_active (action, value);
448
449         for (proxies = gtk_action_get_proxies (GTK_ACTION (action));
450              proxies != NULL; proxies = g_slist_next (proxies)) {
451                 GtkWidget *widget = (GtkWidget *) proxies->data;
452                 gtk_action_unblock_activate_from (GTK_ACTION (action), widget);
453         }
454
455 }
456
457
458 gint 
459 modest_list_index (TnyList *list, GObject *object)
460 {
461         TnyIterator *iter;
462         gint index = 0;
463
464         g_return_val_if_fail (TNY_IS_LIST(list), -1);
465         g_return_val_if_fail (G_IS_OBJECT(object), -1);
466         
467         iter = tny_list_create_iterator (list);
468         while (!tny_iterator_is_done (iter)) {
469                 GObject *current = tny_iterator_get_current (iter);
470
471                 g_object_unref (current);
472                 if (current == object)
473                         break;
474
475                 tny_iterator_next (iter);
476                 index++;
477         }
478
479         if (tny_iterator_is_done (iter))
480                 index = -1;
481         g_object_unref (iter);
482         return index;
483 }
484
485 guint64 
486 modest_utils_get_available_space (const gchar *maildir_path)
487 {
488         gchar *folder;
489         gchar *uri_string;
490         GnomeVFSURI *uri;
491         GnomeVFSFileSize size;
492
493         folder = modest_local_folder_info_get_maildir_path (maildir_path);
494         uri_string = gnome_vfs_get_uri_from_local_path (folder);
495         uri = gnome_vfs_uri_new (uri_string);
496         g_free (folder);
497         g_free (uri_string);
498
499         if (uri) {
500                 if (gnome_vfs_get_volume_free_space (uri, &size) != GNOME_VFS_OK)
501                         size = 0;
502                 gnome_vfs_uri_unref (uri);
503         } else {
504                 size = 0;
505         }
506
507         return (guint64) size;
508 }
509 static void
510 on_destroy_dialog (GtkDialog *dialog)
511 {
512         gtk_widget_destroy (GTK_WIDGET(dialog));
513         if (gtk_events_pending ())
514                 gtk_main_iteration ();
515 }
516
517 static guint
518 checked_modest_sort_criterium_view_add_sort_key (ModestSortCriteriumView *view, const gchar* key, guint max)
519 {
520         gint sort_key;
521         
522         g_return_val_if_fail (view && MODEST_IS_SORT_CRITERIUM_VIEW(view), 0);
523         g_return_val_if_fail (key, 0);
524         
525         sort_key = modest_sort_criterium_view_add_sort_key (view, key);
526         if (sort_key < 0 || sort_key >= max) {
527                 g_warning ("%s: out of range (%d) for %s", __FUNCTION__, sort_key, key);
528                 return 0;
529         } else
530                 return (guint)sort_key; 
531 }
532
533 static void
534 launch_sort_headers_dialog (GtkWindow *parent_window,
535                             GtkDialog *dialog)
536 {
537         ModestHeaderView *header_view = NULL;
538         GList *cols = NULL;
539         GtkSortType sort_type;
540         gint sort_key;
541         gint default_key = 0;
542         gint result;
543         gboolean outgoing = FALSE;
544         gint current_sort_colid = -1;
545         GtkSortType current_sort_type;
546         gint attachments_sort_id;
547         gint priority_sort_id;
548         GtkTreeSortable *sortable;
549         
550         /* Get header window */
551         if (MODEST_IS_MAIN_WINDOW (parent_window)) {
552                 header_view = MODEST_HEADER_VIEW(modest_main_window_get_child_widget (MODEST_MAIN_WINDOW(parent_window),
553                                                                                       MODEST_MAIN_WINDOW_WIDGET_TYPE_HEADER_VIEW));
554 #ifdef MODEST_TOOLKIT_HILDON2
555         } else if (MODEST_IS_HEADER_WINDOW (parent_window)) {
556                 header_view = MODEST_HEADER_VIEW (modest_header_window_get_header_view (MODEST_HEADER_WINDOW (parent_window)));
557 #endif
558
559         }
560         if (!header_view)
561                 return;
562         
563         /* Add sorting keys */
564         cols = modest_header_view_get_columns (header_view);
565         if (cols == NULL) 
566                 return;
567 #define SORT_ID_NUM 6
568         int sort_model_ids[SORT_ID_NUM];
569         int sort_ids[SORT_ID_NUM];
570
571         outgoing = (GPOINTER_TO_INT (g_object_get_data(G_OBJECT(cols->data), MODEST_HEADER_VIEW_COLUMN))==
572                     MODEST_HEADER_VIEW_COLUMN_COMPACT_HEADER_OUT);
573
574         sort_key = checked_modest_sort_criterium_view_add_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), _("mcen_li_sort_sender_recipient"),
575                                                                     SORT_ID_NUM);
576         if (outgoing) {
577                 sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_TO_COLUMN;
578                 sort_ids[sort_key] = MODEST_HEADER_VIEW_COLUMN_COMPACT_HEADER_OUT;
579         } else {
580                 sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_FROM_COLUMN;
581                 sort_ids[sort_key] = MODEST_HEADER_VIEW_COLUMN_COMPACT_HEADER_IN;
582         }
583
584         sort_key = checked_modest_sort_criterium_view_add_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), _("mcen_li_sort_date"),
585                                                             SORT_ID_NUM);
586         if (outgoing) {
587                 sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_DATE_SENT_TIME_T_COLUMN;
588                 sort_ids[sort_key] = MODEST_HEADER_VIEW_COLUMN_COMPACT_SENT_DATE;
589         } else {
590                 sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_DATE_RECEIVED_TIME_T_COLUMN;
591                 sort_ids[sort_key] = MODEST_HEADER_VIEW_COLUMN_COMPACT_RECEIVED_DATE;
592         }
593         default_key = sort_key;
594
595         sort_key = checked_modest_sort_criterium_view_add_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), _("mcen_li_sort_subject"),
596                                                                     SORT_ID_NUM);
597         sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_SUBJECT_COLUMN;
598         if (outgoing)
599                 sort_ids[sort_key] = MODEST_HEADER_VIEW_COLUMN_COMPACT_HEADER_OUT;
600         else
601                 sort_ids[sort_key] = MODEST_HEADER_VIEW_COLUMN_COMPACT_HEADER_IN;
602
603         sort_key = checked_modest_sort_criterium_view_add_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), _("mcen_li_sort_attachment"),
604                                                                     SORT_ID_NUM);
605         sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_FLAGS_COLUMN;
606         sort_ids[sort_key] = TNY_HEADER_FLAG_ATTACHMENTS;
607         attachments_sort_id = sort_key;
608
609         sort_key = checked_modest_sort_criterium_view_add_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), _("mcen_li_sort_size"),
610                                                                     SORT_ID_NUM);
611         sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_MESSAGE_SIZE_COLUMN;
612         sort_ids[sort_key] = 0;
613
614         sort_key = checked_modest_sort_criterium_view_add_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), _("mcen_li_sort_priority"),
615                                                                     SORT_ID_NUM);
616         sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_FLAGS_COLUMN;
617         sort_ids[sort_key] = TNY_HEADER_FLAG_PRIORITY_MASK;
618         priority_sort_id = sort_key;
619         
620         sortable = GTK_TREE_SORTABLE (gtk_tree_model_filter_get_model
621                                       (GTK_TREE_MODEL_FILTER (gtk_tree_view_get_model (GTK_TREE_VIEW (header_view)))));
622         /* Launch dialogs */
623         if (!gtk_tree_sortable_get_sort_column_id (sortable,
624                                                    &current_sort_colid, &current_sort_type)) {
625                 modest_sort_criterium_view_set_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), default_key);
626                 modest_sort_criterium_view_set_sort_order (MODEST_SORT_CRITERIUM_VIEW (dialog), GTK_SORT_DESCENDING);
627         } else {
628                 modest_sort_criterium_view_set_sort_order (MODEST_SORT_CRITERIUM_VIEW (dialog), current_sort_type);
629                 if (current_sort_colid == TNY_GTK_HEADER_LIST_MODEL_FLAGS_COLUMN) {
630                         gpointer flags_sort_type_pointer;
631                         flags_sort_type_pointer = g_object_get_data (G_OBJECT (cols->data), MODEST_HEADER_VIEW_FLAG_SORT);
632                         if (GPOINTER_TO_INT (flags_sort_type_pointer) == TNY_HEADER_FLAG_PRIORITY_MASK)
633                                 modest_sort_criterium_view_set_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), priority_sort_id);
634                         else
635                                 modest_sort_criterium_view_set_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), attachments_sort_id);
636                 } else {
637                         gint current_sort_keyid = 0;
638                         while (current_sort_keyid < SORT_ID_NUM) {
639                                 if (sort_model_ids[current_sort_keyid] == current_sort_colid)
640                                         break;
641                                 else 
642                                         current_sort_keyid++;
643                         }
644                         modest_sort_criterium_view_set_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), current_sort_keyid);
645                 }
646         }
647
648         result = gtk_dialog_run (GTK_DIALOG (dialog));
649         if (result == GTK_RESPONSE_OK) {
650                 sort_key = modest_sort_criterium_view_get_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog));
651                 if (sort_key < 0 || sort_key > SORT_ID_NUM -1) {
652                         g_warning ("%s: out of range (%d)", __FUNCTION__, sort_key);
653                         sort_key = 0;
654                 }
655
656                 sort_type = modest_sort_criterium_view_get_sort_order (MODEST_SORT_CRITERIUM_VIEW (dialog));
657                 if (sort_model_ids[sort_key] == TNY_GTK_HEADER_LIST_MODEL_FLAGS_COLUMN) {
658                         g_object_set_data (G_OBJECT(cols->data), MODEST_HEADER_VIEW_FLAG_SORT,
659                                            GINT_TO_POINTER (sort_ids[sort_key]));
660                         /* This is a hack to make it resort rows always when flag fields are
661                          * selected. If we do not do this, changing sort field from priority to
662                          * attachments does not work */
663                         modest_header_view_sort_by_column_id (header_view, 0, sort_type);
664                 } else {
665                         gtk_tree_view_column_set_sort_column_id (GTK_TREE_VIEW_COLUMN (cols->data), 
666                                                                  sort_model_ids[sort_key]);
667                 }
668
669                 modest_header_view_sort_by_column_id (header_view, sort_model_ids[sort_key], sort_type);
670                 gtk_tree_sortable_sort_column_changed (sortable);
671         }
672
673         modest_widget_memory_save (modest_runtime_get_conf (),
674                                    G_OBJECT (header_view), MODEST_CONF_HEADER_VIEW_KEY);
675         
676         /* free */
677         g_list_free(cols);      
678 }
679
680 void
681 modest_utils_run_sort_dialog (GtkWindow *parent_window,
682                               ModestSortDialogType type)
683 {
684         GtkWidget *dialog = NULL;
685
686         /* Build dialog */
687         dialog = modest_platform_create_sort_dialog (parent_window);
688         if (dialog == NULL)
689                 return;
690         modest_window_mgr_set_modal (modest_runtime_get_window_mgr (),
691                                      GTK_WINDOW (dialog), parent_window);
692
693         /* Fill sort keys */
694         switch (type) {
695         case MODEST_SORT_HEADERS:
696                 launch_sort_headers_dialog (parent_window, 
697                                             GTK_DIALOG(dialog));
698                 break;
699         }
700         
701         /* Free */
702         on_destroy_dialog (GTK_DIALOG(dialog));
703 }
704
705
706 gchar *
707 modest_images_cache_get_id (const gchar *account, const gchar *uri)
708 {
709         GnomeVFSURI *vfs_uri;
710         gchar *result;
711  
712         vfs_uri = gnome_vfs_uri_new (uri);
713         if (vfs_uri == NULL)
714                 return NULL;
715  
716         result = g_strdup_printf ("%s__%x", account, gnome_vfs_uri_hash (vfs_uri));
717         gnome_vfs_uri_unref (vfs_uri);
718  
719         return result;
720 }
721
722 gchar *
723 modest_utils_get_account_name_from_recipient (const gchar *from_header, gchar **mailbox)
724 {
725         gchar *account_name = NULL;
726         ModestAccountMgr *mgr = NULL;
727         GSList *accounts = NULL, *node = NULL;
728
729         if (mailbox)
730                 *mailbox = NULL;
731         g_return_val_if_fail (from_header, NULL);
732
733         mgr = modest_runtime_get_account_mgr ();
734         accounts = modest_account_mgr_account_names (mgr, TRUE);
735                 
736         for (node = accounts; node != NULL; node = g_slist_next (node)) {
737                 gchar *from;
738                 gchar *transport_account;
739
740                 if (!strcmp (from_header, node->data)) {
741                         account_name = g_strdup (node->data);
742                         break;
743                 }
744
745                 from = 
746                         modest_account_mgr_get_from_string (mgr, node->data, NULL);
747                         
748                 if (from) {
749                         gchar *from_email = 
750                                 modest_text_utils_get_email_address (from);
751                         gchar *from_header_email =
752                                 modest_text_utils_get_email_address (from_header);
753                                 
754                         if (from_email && from_header_email) {
755                                 if (!modest_text_utils_utf8_strcmp (from_header_email, from_email, TRUE)) {
756                                         account_name = g_strdup (node->data);
757                                         g_free (from);
758                                         g_free (from_email);
759                                         break;
760                                 }
761                         }
762                         g_free (from_email);
763                         g_free (from_header_email);
764                         g_free (from);
765                 }
766
767                 transport_account = modest_account_mgr_get_server_account_name (modest_runtime_get_account_mgr (),
768                                                                                 (const gchar *) node->data,
769                                                                                 TNY_ACCOUNT_TYPE_TRANSPORT);
770                 if (transport_account) {
771                         gchar *proto;
772                         proto = modest_account_mgr_get_string (mgr, transport_account, MODEST_ACCOUNT_PROTO, TRUE);
773
774                         if (proto != NULL) {
775                                 ModestProtocol *protocol = 
776                                         modest_protocol_registry_get_protocol_by_name (modest_runtime_get_protocol_registry (),
777                                                                                        MODEST_PROTOCOL_REGISTRY_TRANSPORT_PROTOCOLS,
778                                                                                        proto);
779                                 if (protocol && MODEST_IS_ACCOUNT_PROTOCOL (protocol)) {
780                                         ModestPairList *pair_list;
781                                         ModestPair *pair;
782                                         gchar *from_header_email =
783                                                 modest_text_utils_get_email_address (from_header);
784                                         pair_list = modest_account_protocol_get_from_list (MODEST_ACCOUNT_PROTOCOL (protocol),
785                                                                                            node->data);
786                                         
787                                         pair = modest_pair_list_find_by_first_as_string (pair_list, from_header_email);
788                                         if (pair != NULL) {
789                                                 account_name = g_strdup (node->data);
790                                                 if (mailbox)
791                                                         *mailbox = g_strdup (from_header_email);
792                                         }
793                                         
794                                         modest_pair_list_free (pair_list);
795                                         
796                                 }
797                                 g_free (proto);
798                         }
799                         g_free (transport_account);
800                 }
801                 if (mailbox && *mailbox)
802                         break;
803                         
804         }
805         g_slist_foreach (accounts, (GFunc) g_free, NULL);
806         g_slist_free (accounts);
807
808         return account_name;
809 }
810
811 void 
812 modest_utils_on_entry_invalid_character (ModestValidatingEntry *self, 
813                                          const gchar* character,
814                                          gpointer user_data)
815 {
816         gchar *message = NULL;
817         const gchar *show_char = NULL;
818
819         if (character)
820                 show_char = character;
821         else {
822                 show_char = "' '";
823         }
824         
825         message = g_strdup_printf (_CS("ckdg_ib_illegal_characters_entered"), show_char);
826         modest_platform_information_banner (GTK_WIDGET (self), NULL, message);
827         g_free (message);
828 }