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