* Lots of build fixes due to a very bad commit with the merge not
[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
55 GQuark
56 modest_utils_get_supported_secure_authentication_error_quark (void)
57 {
58         return g_quark_from_static_string("modest-utils-get-supported-secure-authentication-error-quark");
59 }
60
61 gboolean 
62 modest_utils_folder_writable (const gchar *filename)
63 {
64         g_return_val_if_fail (filename, FALSE);
65
66         if (!filename)
67                 return FALSE;
68         
69         if (g_strncasecmp (filename, "obex", 4) != 0) {
70                 GnomeVFSFileInfo *folder_info;
71                 gchar *folder;
72                 folder = g_path_get_dirname (filename);
73                 folder_info = gnome_vfs_file_info_new ();
74                 gnome_vfs_get_file_info (folder, folder_info,
75                                          GNOME_VFS_FILE_INFO_GET_ACCESS_RIGHTS);
76                 g_free (folder);
77                 if (!((folder_info->permissions & GNOME_VFS_PERM_ACCESS_WRITABLE) ||
78                       (folder_info->permissions & GNOME_VFS_PERM_USER_WRITE))) {
79                         return FALSE;
80                 }
81                 gnome_vfs_file_info_unref (folder_info);
82         }
83         return TRUE;
84 }
85
86 gboolean 
87 modest_utils_file_exists (const gchar *filename)
88 {
89         GnomeVFSURI *uri = NULL;
90         gboolean result = FALSE;
91
92         g_return_val_if_fail (filename, FALSE);
93         
94         uri = gnome_vfs_uri_new (filename);
95         if (uri) {
96                 result = gnome_vfs_uri_exists (uri);
97                 gnome_vfs_uri_unref (uri);
98         }
99         return result;
100 }
101
102 TnyFsStream *
103 modest_utils_create_temp_stream (const gchar *orig_name, const gchar *hash_base, gchar **path)
104 {
105         gint fd;
106         gchar *filepath = NULL;
107         gchar *tmpdir;
108         guint hash_number;
109
110         /* hmmm... maybe we need a modest_text_utils_validate_file_name? */
111         g_return_val_if_fail (orig_name && strlen(orig_name) != 0, NULL);
112
113         if (strlen(orig_name) > 200) {
114                 g_warning ("%s: filename too long ('%s')",
115                            __FUNCTION__, orig_name);
116                 return NULL;
117         }
118         
119         if (g_strstr_len (orig_name, strlen(orig_name), "/") != NULL) {
120                 g_warning ("%s: filename contains '/' character(s) (%s)",
121                            __FUNCTION__, orig_name);
122                 return NULL;
123         }
124                 
125         /* make a random subdir under /tmp or /var/tmp */
126         if (hash_base != NULL) {
127                 hash_number = g_str_hash (hash_base);
128         } else {
129                 hash_number = (guint) random ();
130         }
131         tmpdir = g_strdup_printf ("%s/%u", g_get_tmp_dir (), hash_number);
132         if ((g_access (tmpdir, R_OK) == -1) && (g_mkdir (tmpdir, 0755) == -1)) {
133                 g_warning ("%s: failed to create dir '%s': %s",
134                            __FUNCTION__, tmpdir, g_strerror(errno));
135                 g_free (tmpdir);
136                 return NULL;
137         }
138
139         filepath = g_strconcat (tmpdir, "/", orig_name, NULL);
140         /* don't overwrite if it already exists, even if it is writable */
141         if (modest_utils_file_exists (filepath)) {
142                 if (path!=NULL) {
143                         *path = filepath;
144                 } else {
145                         g_free (filepath);
146                 }
147                 g_free (tmpdir);
148                 return NULL;
149         } else {
150                 /* try to write the file there */
151                 fd = g_open (filepath, O_CREAT|O_WRONLY|O_TRUNC, 0644);
152                 if (fd == -1) {
153                         g_warning ("%s: failed to create '%s': %s",
154                                         __FUNCTION__, filepath, g_strerror(errno));                     
155                         g_free (filepath);
156                         g_free (tmpdir);
157                         return NULL;
158                 }
159         }
160
161         g_free (tmpdir);
162
163         if (path)
164                 *path = filepath;
165
166         return TNY_FS_STREAM (tny_fs_stream_new (fd));
167 }
168
169 typedef struct 
170 {
171         gboolean cancel;
172         GList *result;
173         GtkWidget* dialog;
174         GtkWidget* progress;
175         GError* error;
176 } ModestGetSupportedAuthInfo;
177
178 static void on_camel_account_get_supported_secure_authentication_status (
179         GObject *self, TnyStatus *status, gpointer user_data)
180 {
181         /*ModestGetSupportedAuthInfo* info = (ModestGetSupportedAuthInfo*) user_data;*/
182 }
183
184 static gboolean
185 on_idle_secure_auth_finished (gpointer user_data)
186 {
187         ModestGetSupportedAuthInfo *info = (ModestGetSupportedAuthInfo*)user_data;
188         /* Operation has finished, close the dialog. Control continues after
189          * gtk_dialog_run in modest_utils_get_supported_secure_authentication_methods() */
190
191         /* This is a GDK lock because we are an idle callback and
192          * the code below is or does Gtk+ code */
193
194         gdk_threads_enter(); /* CHECKED */
195         gtk_dialog_response (GTK_DIALOG (info->dialog), GTK_RESPONSE_ACCEPT);
196         gdk_threads_leave(); /* CHECKED */
197
198         return FALSE;
199 }
200
201 static void
202 on_camel_account_get_supported_secure_authentication (TnyCamelAccount *self, gboolean cancelled,
203         TnyList *auth_types, GError *err, gpointer user_data)
204 {
205         g_return_if_fail (TNY_IS_CAMEL_ACCOUNT(self));
206         g_return_if_fail (TNY_IS_LIST(auth_types));
207         
208         ModestGetSupportedAuthInfo *info = (ModestGetSupportedAuthInfo*)user_data;
209         g_return_if_fail (info);
210         
211
212         /* Free everything if the actual action was canceled */
213         if (info->cancel) {
214                 /* The operation was canceled and the ownership of the info given to us
215                  * so that we could still check the cancel flag. */
216                 g_slice_free (ModestGetSupportedAuthInfo, info);
217                 info = NULL;
218         }
219         else
220         {
221                 if (err) {
222                         if (info->error) {
223                                 g_error_free (info->error);
224                                 info->error = NULL;
225                         }
226                         
227                         info->error = g_error_copy (err);
228                 }
229
230                 if (!auth_types) {
231                         g_warning ("DEBUG: %s: auth_types is NULL.\n", __FUNCTION__);
232                 }
233                 else if (tny_list_get_length(auth_types) == 0) 
234                         g_warning ("DEBUG: %s: auth_types is an empty TnyList.\n", __FUNCTION__);
235                 else {
236                         ModestPairList *pairs;
237                         GList *result;
238                         ModestProtocolRegistry *protocol_registry;
239
240                         protocol_registry = modest_runtime_get_protocol_registry ();
241                         pairs = modest_protocol_registry_get_pair_list_by_tag (protocol_registry, MODEST_PROTOCOL_REGISTRY_AUTH_PROTOCOLS);
242   
243                         /* Get the enum value for the strings: */
244                         result = NULL;
245                         TnyIterator* iter = tny_list_create_iterator(auth_types);
246                         while (!tny_iterator_is_done(iter)) {
247                                 TnyPair *pair;
248                                 const gchar *auth_name;
249                                 ModestProtocolType protocol_type;
250
251                                 pair = TNY_PAIR(tny_iterator_get_current(iter));
252                                 auth_name = NULL;
253                                 if (pair) {
254                                         auth_name = tny_pair_get_name(pair);
255                                         g_object_unref (pair);
256                                         pair = NULL;
257                                 }
258
259                                 printf("DEBUG: %s: auth_name=%s\n", __FUNCTION__, auth_name);
260
261                                 protocol_type = modest_protocol_get_type_id (modest_protocol_registry_get_protocol_by_name (protocol_registry,
262                                                                                                                             MODEST_PROTOCOL_REGISTRY_AUTH_PROTOCOLS,
263                                                                                                                             auth_name));
264
265                                 if(modest_protocol_registry_protocol_type_is_secure (protocol_registry, protocol_type))
266                                                 result = g_list_prepend(result, GINT_TO_POINTER(protocol_type));
267
268                                 tny_iterator_next(iter);
269                         }
270                         g_object_unref (iter);
271
272                         modest_pair_list_free (pairs);
273         
274                         info->result = result;
275                 }
276
277                 printf("DEBUG: finished\n");
278                                 
279                 /* Close the dialog in a main thread */
280                 g_idle_add(on_idle_secure_auth_finished, info);
281         }
282 }
283
284 static void
285 on_secure_auth_cancel(GtkWidget* dialog, int response, gpointer user_data)
286 {
287         g_return_if_fail (GTK_IS_WIDGET(dialog));
288         
289         if(response == GTK_RESPONSE_REJECT || response == GTK_RESPONSE_DELETE_EVENT) {
290                 ModestGetSupportedAuthInfo *info = (ModestGetSupportedAuthInfo*)user_data;
291                 g_return_if_fail(info);
292                 /* This gives the ownership of the info to the worker thread. */
293                 info->result = NULL;
294                 info->cancel = TRUE;
295         }
296 }
297 typedef struct {
298         GtkProgressBar *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         gtk_progress_bar_pulse (info->progress);
308
309         if (!info->not_finished) {
310                 g_object_unref (info->progress);
311                 g_slice_free (KeepPulsing, info);
312                 return FALSE;
313         }
314         
315         return TRUE;
316 }
317
318 GList*
319 modest_utils_get_supported_secure_authentication_methods (ModestProtocolType protocol_type, 
320         const gchar* hostname, gint port, const gchar* username, GtkWindow *parent_window, GError** error)
321 {
322         TnyAccount * tny_account = NULL;
323         ModestProtocolRegistry *protocol_registry;
324         ModestProtocol *protocol;
325
326         g_return_val_if_fail (protocol_type != MODEST_PROTOCOL_REGISTRY_TYPE_INVALID, NULL);
327
328         protocol_registry = modest_runtime_get_protocol_registry ();
329         
330         /* We need a connection to get the capabilities; */
331         if (!modest_platform_connect_and_wait (GTK_WINDOW (parent_window), NULL))
332                 return NULL;
333          
334         /*
335         result = g_list_append (result, GINT_TO_POINTER (MODEST_PROTOCOL_AUTH_CRAMMD5));
336         */
337         
338         /* Create a TnyCamelAccount so we can use 
339          * tny_camel_account_get_supported_secure_authentication(): */
340         protocol = modest_protocol_registry_get_protocol_by_type (protocol_registry, protocol_type);
341         tny_account = NULL;
342         if (MODEST_IS_ACCOUNT_PROTOCOL (protocol)) {
343                 tny_account = modest_account_protocol_create_account (MODEST_ACCOUNT_PROTOCOL (protocol));
344         }
345         
346         if (!tny_account) {
347                 g_printerr ("%s could not create tny account.", __FUNCTION__);
348                 return NULL;
349         }
350         
351         /* Set proto, so that the prepare_func() vfunc will work when we call 
352          * set_session(): */
353          /* TODO: Why isn't this done in account_new()? */
354         tny_account_set_proto (tny_account,
355                                modest_protocol_get_name (modest_protocol_registry_get_protocol_by_type (protocol_registry, protocol_type)));
356
357         tny_account_set_hostname (tny_account, hostname);
358         /* Required for POP, at least */
359         tny_account_set_user (tny_account, username);
360                                
361         if(port > 0)
362                 tny_account_set_port (tny_account, port);
363                 
364         /* Set the session for the account, so we can use it: */
365         ModestTnyAccountStore *account_store = modest_runtime_get_account_store ();
366         TnySessionCamel *session = 
367                 modest_tny_account_store_get_session (TNY_ACCOUNT_STORE (account_store));
368         g_return_val_if_fail (session, NULL);
369         tny_camel_account_set_session (TNY_CAMEL_ACCOUNT(tny_account), session);
370         
371         
372         /* Ask camel to ask the server, asynchronously: */
373         ModestGetSupportedAuthInfo *info = g_slice_new (ModestGetSupportedAuthInfo);
374         info->result = NULL;
375         info->cancel = FALSE;
376         info->error = NULL;
377         info->progress = gtk_progress_bar_new();
378
379         /* FIXME: the title (first arg) here is empty; there should be 'accountwizard_fi_authentication', 
380          *  but that does not exist yet; see bug #82487. so, for now, we simply leave it empty
381          */
382         info->dialog = gtk_dialog_new_with_buttons(" ", 
383                                                    parent_window, GTK_DIALOG_MODAL,
384                                                    _("mcen_bd_dialog_cancel"),
385                                                    GTK_RESPONSE_REJECT,
386                                                    NULL);
387         //gtk_window_set_default_size(GTK_WINDOW(info->dialog), 300, 100);
388         
389         g_signal_connect(G_OBJECT(info->dialog), "response", G_CALLBACK(on_secure_auth_cancel), info);
390         
391         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(info->dialog)->vbox),
392                           gtk_label_new(_("emev_ni_checking_supported_auth_methods")));
393         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(info->dialog)->vbox), info->progress);
394         gtk_widget_show_all(info->dialog);
395
396         KeepPulsing *pi = g_slice_new (KeepPulsing);
397         pi->progress = (GtkProgressBar *) g_object_ref (info->progress);
398         pi->not_finished = TRUE;
399         
400         /* Starts the pulsing of the progressbar */
401         g_timeout_add (500, keep_pulsing, pi);
402         
403         printf ("DEBUG: %s: STARTING.\n", __FUNCTION__);
404         
405         tny_camel_account_get_supported_secure_authentication (
406                 TNY_CAMEL_ACCOUNT (tny_account),
407                 on_camel_account_get_supported_secure_authentication,
408                 on_camel_account_get_supported_secure_authentication_status,
409                 info);
410
411         gtk_dialog_run (GTK_DIALOG (info->dialog));
412         
413         pi->not_finished = FALSE;
414         /* pi is freed in the timeout itself to avoid a GCond here */
415         
416         gtk_widget_destroy(info->dialog);
417                         
418         GList *result = info->result;
419         if (!info->cancel)
420         {
421                 if (info->error) {
422                         gchar * debug_url_string = tny_account_get_url_string  (tny_account);
423                         g_warning ("DEBUG: %s:\n  error: %s\n  account url: %s", __FUNCTION__, info->error->message, 
424                                 debug_url_string);
425                         g_free (debug_url_string);
426                         
427                         g_propagate_error(error, info->error);
428                         info->error = NULL;
429                 }
430
431                 g_slice_free (ModestGetSupportedAuthInfo, info);
432                 info = NULL;
433         }
434         else
435         {
436                 // Tell the caller that the operation was canceled so it can
437                 // make a difference
438                 g_set_error(error,
439                             modest_utils_get_supported_secure_authentication_error_quark(),
440                             MODEST_UTILS_GET_SUPPORTED_SECURE_AUTHENTICATION_ERROR_CANCELED,
441                             "User has canceled query");
442         }
443
444         return result;
445 }
446
447 void 
448 modest_utils_show_dialog_and_forget (GtkWindow *parent_window, 
449                                      GtkDialog *dialog)
450 {
451         g_return_if_fail (GTK_IS_WINDOW(parent_window));
452         g_return_if_fail (GTK_IS_DIALOG(dialog));
453
454         gtk_window_set_transient_for (GTK_WINDOW (dialog), parent_window);
455         
456         /* Destroy the dialog when it is closed: */
457         g_signal_connect_swapped (dialog, 
458                                   "response", 
459                                   G_CALLBACK (gtk_widget_destroy), 
460                                   dialog);
461
462         gtk_widget_show (GTK_WIDGET (dialog));
463 }
464
465 void
466 modest_utils_toggle_action_set_active_block_notify (GtkToggleAction *action, gboolean value)
467 {
468         GSList *proxies = NULL;
469
470         g_return_if_fail (GTK_IS_TOGGLE_ACTION (action));
471
472         for (proxies = gtk_action_get_proxies (GTK_ACTION (action));
473              proxies != NULL; proxies = g_slist_next (proxies)) {
474                 GtkWidget *widget = (GtkWidget *) proxies->data;
475                 gtk_action_block_activate_from (GTK_ACTION (action), widget);
476         }
477
478         gtk_toggle_action_set_active (action, value);
479
480         for (proxies = gtk_action_get_proxies (GTK_ACTION (action));
481              proxies != NULL; proxies = g_slist_next (proxies)) {
482                 GtkWidget *widget = (GtkWidget *) proxies->data;
483                 gtk_action_unblock_activate_from (GTK_ACTION (action), widget);
484         }
485
486 }
487
488
489 gint 
490 modest_list_index (TnyList *list, GObject *object)
491 {
492         TnyIterator *iter;
493         gint index = 0;
494
495         g_return_val_if_fail (TNY_IS_LIST(list), -1);
496         g_return_val_if_fail (G_IS_OBJECT(object), -1);
497         
498         iter = tny_list_create_iterator (list);
499         while (!tny_iterator_is_done (iter)) {
500                 GObject *current = tny_iterator_get_current (iter);
501
502                 g_object_unref (current);
503                 if (current == object)
504                         break;
505
506                 tny_iterator_next (iter);
507                 index++;
508         }
509
510         if (tny_iterator_is_done (iter))
511                 index = -1;
512         g_object_unref (iter);
513         return index;
514 }
515
516 guint64 
517 modest_utils_get_available_space (const gchar *maildir_path)
518 {
519         gchar *folder;
520         gchar *uri_string;
521         GnomeVFSURI *uri;
522         GnomeVFSFileSize size;
523
524         folder = modest_local_folder_info_get_maildir_path (maildir_path);
525         uri_string = gnome_vfs_get_uri_from_local_path (folder);
526         uri = gnome_vfs_uri_new (uri_string);
527         g_free (folder);
528         g_free (uri_string);
529
530         if (uri) {
531                 if (gnome_vfs_get_volume_free_space (uri, &size) != GNOME_VFS_OK)
532                         size = 0;
533                 gnome_vfs_uri_unref (uri);
534         } else {
535                 size = 0;
536         }
537
538         return (guint64) size;
539 }
540 static void
541 on_destroy_dialog (GtkDialog *dialog)
542 {
543         gtk_widget_destroy (GTK_WIDGET(dialog));
544         if (gtk_events_pending ())
545                 gtk_main_iteration ();
546 }
547
548 static guint
549 checked_modest_sort_criterium_view_add_sort_key (ModestSortCriteriumView *view, const gchar* key, guint max)
550 {
551         gint sort_key;
552         
553         g_return_val_if_fail (view && MODEST_IS_SORT_CRITERIUM_VIEW(view), 0);
554         g_return_val_if_fail (key, 0);
555         
556         sort_key = modest_sort_criterium_view_add_sort_key (view, key);
557         if (sort_key < 0 || sort_key >= max) {
558                 g_warning ("%s: out of range (%d) for %s", __FUNCTION__, sort_key, key);
559                 return 0;
560         } else
561                 return (guint)sort_key; 
562 }
563
564 static void
565 launch_sort_headers_dialog (GtkWindow *parent_window,
566                             GtkDialog *dialog)
567 {
568         ModestHeaderView *header_view = NULL;
569         GList *cols = NULL;
570         GtkSortType sort_type;
571         gint sort_key;
572         gint default_key = 0;
573         gint result;
574         gboolean outgoing = FALSE;
575         gint current_sort_colid = -1;
576         GtkSortType current_sort_type;
577         gint attachments_sort_id;
578         gint priority_sort_id;
579         GtkTreeSortable *sortable;
580         
581         /* Get header window */
582         if (MODEST_IS_MAIN_WINDOW (parent_window)) {
583                 header_view = MODEST_HEADER_VIEW(modest_main_window_get_child_widget (MODEST_MAIN_WINDOW(parent_window),
584                                                                                       MODEST_MAIN_WINDOW_WIDGET_TYPE_HEADER_VIEW));
585         }
586         if (!header_view)
587                 return;
588         
589         /* Add sorting keys */
590         cols = modest_header_view_get_columns (header_view);
591         if (cols == NULL) 
592                 return;
593 #define SORT_ID_NUM 6
594         int sort_model_ids[SORT_ID_NUM];
595         int sort_ids[SORT_ID_NUM];
596
597         outgoing = (GPOINTER_TO_INT (g_object_get_data(G_OBJECT(cols->data), MODEST_HEADER_VIEW_COLUMN))==
598                     MODEST_HEADER_VIEW_COLUMN_COMPACT_HEADER_OUT);
599
600         sort_key = checked_modest_sort_criterium_view_add_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), _("mcen_li_sort_sender_recipient"),
601                                                                     SORT_ID_NUM);
602         if (outgoing) {
603                 sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_TO_COLUMN;
604                 sort_ids[sort_key] = MODEST_HEADER_VIEW_COLUMN_COMPACT_HEADER_OUT;
605         } else {
606                 sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_FROM_COLUMN;
607                 sort_ids[sort_key] = MODEST_HEADER_VIEW_COLUMN_COMPACT_HEADER_IN;
608         }
609
610         sort_key = checked_modest_sort_criterium_view_add_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), _("mcen_li_sort_date"),
611                                                             SORT_ID_NUM);
612         if (outgoing) {
613                 sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_DATE_SENT_TIME_T_COLUMN;
614                 sort_ids[sort_key] = MODEST_HEADER_VIEW_COLUMN_COMPACT_SENT_DATE;
615         } else {
616                 sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_DATE_RECEIVED_TIME_T_COLUMN;
617                 sort_ids[sort_key] = MODEST_HEADER_VIEW_COLUMN_COMPACT_RECEIVED_DATE;
618         }
619         default_key = sort_key;
620
621         sort_key = checked_modest_sort_criterium_view_add_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), _("mcen_li_sort_subject"),
622                                                                     SORT_ID_NUM);
623         sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_SUBJECT_COLUMN;
624         if (outgoing)
625                 sort_ids[sort_key] = MODEST_HEADER_VIEW_COLUMN_COMPACT_HEADER_OUT;
626         else
627                 sort_ids[sort_key] = MODEST_HEADER_VIEW_COLUMN_COMPACT_HEADER_IN;
628
629         sort_key = checked_modest_sort_criterium_view_add_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), _("mcen_li_sort_attachment"),
630                                                                     SORT_ID_NUM);
631         sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_FLAGS_COLUMN;
632         sort_ids[sort_key] = TNY_HEADER_FLAG_ATTACHMENTS;
633         attachments_sort_id = sort_key;
634
635         sort_key = checked_modest_sort_criterium_view_add_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), _("mcen_li_sort_size"),
636                                                                     SORT_ID_NUM);
637         sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_MESSAGE_SIZE_COLUMN;
638         sort_ids[sort_key] = 0;
639
640         sort_key = checked_modest_sort_criterium_view_add_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), _("mcen_li_sort_priority"),
641                                                                     SORT_ID_NUM);
642         sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_FLAGS_COLUMN;
643         sort_ids[sort_key] = TNY_HEADER_FLAG_PRIORITY_MASK;
644         priority_sort_id = sort_key;
645         
646         sortable = GTK_TREE_SORTABLE (gtk_tree_model_filter_get_model
647                                       (GTK_TREE_MODEL_FILTER (gtk_tree_view_get_model (GTK_TREE_VIEW (header_view)))));
648         /* Launch dialogs */
649         if (!gtk_tree_sortable_get_sort_column_id (sortable,
650                                                    &current_sort_colid, &current_sort_type)) {
651                 modest_sort_criterium_view_set_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), default_key);
652                 modest_sort_criterium_view_set_sort_order (MODEST_SORT_CRITERIUM_VIEW (dialog), GTK_SORT_DESCENDING);
653         } else {
654                 modest_sort_criterium_view_set_sort_order (MODEST_SORT_CRITERIUM_VIEW (dialog), current_sort_type);
655                 if (current_sort_colid == TNY_GTK_HEADER_LIST_MODEL_FLAGS_COLUMN) {
656                         gpointer flags_sort_type_pointer;
657                         flags_sort_type_pointer = g_object_get_data (G_OBJECT (cols->data), MODEST_HEADER_VIEW_FLAG_SORT);
658                         if (GPOINTER_TO_INT (flags_sort_type_pointer) == TNY_HEADER_FLAG_PRIORITY_MASK)
659                                 modest_sort_criterium_view_set_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), priority_sort_id);
660                         else
661                                 modest_sort_criterium_view_set_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), attachments_sort_id);
662                 } else {
663                         gint current_sort_keyid = 0;
664                         while (current_sort_keyid < 6) {
665                                 if (sort_model_ids[current_sort_keyid] == current_sort_colid)
666                                         break;
667                                 else 
668                                         current_sort_keyid++;
669                         }
670                         modest_sort_criterium_view_set_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), current_sort_keyid);
671                 }
672         }
673
674         result = gtk_dialog_run (GTK_DIALOG (dialog));
675         if (result == GTK_RESPONSE_OK) {
676                 sort_key = modest_sort_criterium_view_get_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog));
677                 if (sort_key < 0 || sort_key > SORT_ID_NUM -1) {
678                         g_warning ("%s: out of range (%d)", __FUNCTION__, sort_key);
679                         sort_key = 0;
680                 }
681
682                 sort_type = modest_sort_criterium_view_get_sort_order (MODEST_SORT_CRITERIUM_VIEW (dialog));
683                 if (sort_model_ids[sort_key] == TNY_GTK_HEADER_LIST_MODEL_FLAGS_COLUMN) {
684                         g_object_set_data (G_OBJECT(cols->data), MODEST_HEADER_VIEW_FLAG_SORT,
685                                            GINT_TO_POINTER (sort_ids[sort_key]));
686                         /* This is a hack to make it resort rows always when flag fields are
687                          * selected. If we do not do this, changing sort field from priority to
688                          * attachments does not work */
689                         modest_header_view_sort_by_column_id (header_view, 0, sort_type);
690                 } else {
691                         gtk_tree_view_column_set_sort_column_id (GTK_TREE_VIEW_COLUMN (cols->data), 
692                                                                  sort_model_ids[sort_key]);
693                 }
694
695                 modest_header_view_sort_by_column_id (header_view, sort_model_ids[sort_key], sort_type);
696                 gtk_tree_sortable_sort_column_changed (sortable);
697         }
698
699         modest_widget_memory_save (modest_runtime_get_conf (),
700                                    G_OBJECT (header_view), MODEST_CONF_HEADER_VIEW_KEY);
701         
702         /* free */
703         g_list_free(cols);      
704 }
705
706 void
707 modest_utils_run_sort_dialog (GtkWindow *parent_window,
708                                  ModestSortDialogType type)
709 {
710         GtkWidget *dialog = NULL;
711
712         /* Build dialog */
713         dialog = modest_platform_create_sort_dialog (parent_window);
714         if (dialog == NULL)
715                 return;
716         modest_window_mgr_set_modal (modest_runtime_get_window_mgr (),
717                                      GTK_WINDOW (dialog));
718
719         /* Fill sort keys */
720         switch (type) {
721         case MODEST_SORT_HEADERS:
722                 launch_sort_headers_dialog (parent_window, 
723                                             GTK_DIALOG(dialog));
724                 break;
725         }
726         
727         /* Free */
728         on_destroy_dialog (GTK_DIALOG(dialog));
729 }
730
731
732 gchar *
733 modest_images_cache_get_id (const gchar *account, const gchar *uri)
734 {
735         GnomeVFSURI *vfs_uri;
736         gchar *result;
737  
738         vfs_uri = gnome_vfs_uri_new (uri);
739         if (vfs_uri == NULL)
740                 return NULL;
741  
742         result = g_strdup_printf ("%s__%x", account, gnome_vfs_uri_hash (vfs_uri));
743         gnome_vfs_uri_unref (vfs_uri);
744  
745         return result;
746 }
747
748 gchar *
749 modest_utils_get_account_name_from_recipient (const gchar *from_header)
750 {
751         gchar *account_name = NULL;
752         ModestAccountMgr *mgr = NULL;
753         GSList *accounts = NULL, *node = NULL;
754
755         g_return_val_if_fail (from_header, NULL);
756
757         mgr = modest_runtime_get_account_mgr ();
758         accounts = modest_account_mgr_account_names (mgr, TRUE);
759                 
760         for (node = accounts; node != NULL; node = g_slist_next (node)) {
761                 gchar *from = 
762                         modest_account_mgr_get_from_string (mgr, node->data);
763                         
764                 if (from) {
765                         gchar *from_email = 
766                                 modest_text_utils_get_email_address (from);
767                                 
768                         if (from_email) {
769                                 if (!modest_text_utils_utf8_strcmp (from_header, from_email, TRUE)) {
770                                         account_name = g_strdup (node->data);
771                                         g_free (from);
772                                         g_free (from_email);
773                                         break;
774                                 }
775                                 g_free (from_email);
776                         }
777                         g_free (from);
778                 }
779         }
780         g_slist_foreach (accounts, (GFunc) g_free, NULL);
781         g_slist_free (accounts);
782
783         return account_name;
784 }
785
786 void 
787 modest_utils_on_entry_invalid_character (ModestValidatingEntry *self, 
788                                          const gchar* character,
789                                          gpointer user_data)
790 {
791         gchar *message = NULL;
792         const gchar *show_char = NULL;
793
794         if (character)
795                 show_char = character;
796         else {
797                 show_char = "' '";
798         }
799         
800         message = g_strdup_printf (_CS("ckdg_ib_illegal_characters_entered"), show_char);
801         modest_platform_information_banner (GTK_WIDGET (self), NULL, message);
802         g_free (message);
803 }