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