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