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