Fix modest_utils_show_dialog_and_forget for gtk and modest shell
[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-send-queue.h>
40 #include <tny-camel-transport-account.h>
41 #include <tny-camel-imap-store-account.h>
42 #include <tny-camel-pop-store-account.h>
43 #include <locale.h>
44 #include <modest-defs.h>
45 #include "modest-utils.h"
46 #include "modest-platform.h"
47 #include <modest-account-protocol.h>
48 #include "modest-account-mgr-helpers.h"
49 #include "modest-text-utils.h"
50 #include <modest-local-folder-info.h>
51 #include "widgets/modest-header-view.h"
52 #include "widgets/modest-main-window.h"
53 #include "modest-widget-memory.h"
54 #include "widgets/modest-sort-criterium-view.h"
55 #include "widgets/modest-header-window.h"
56 #ifdef MODEST_TOOLKIT_GTK
57 #include <modest-gtk-window-mgr.h>
58 #endif
59 #include <langinfo.h>
60
61 GQuark
62 modest_utils_get_supported_secure_authentication_error_quark (void)
63 {
64         return g_quark_from_static_string("modest-utils-get-supported-secure-authentication-error-quark");
65 }
66
67 gboolean
68 modest_utils_folder_writable (const gchar *filename)
69 {
70         g_return_val_if_fail (filename, FALSE);
71
72         if (!filename)
73                 return FALSE;
74
75         if (g_ascii_strncasecmp (filename, "obex", 4) != 0) {
76                 GnomeVFSFileInfo *folder_info = NULL;
77                 GnomeVFSResult result = GNOME_VFS_OK;
78                 GnomeVFSURI *uri = NULL;
79                 GnomeVFSURI *folder_uri = NULL;
80
81                 uri = gnome_vfs_uri_new (filename);
82                 folder_uri = gnome_vfs_uri_get_parent (uri);
83
84                 if (folder_uri != NULL) {
85                         folder_info = gnome_vfs_file_info_new ();
86                         result = gnome_vfs_get_file_info_uri (folder_uri, folder_info,
87                                                               GNOME_VFS_FILE_INFO_GET_ACCESS_RIGHTS);
88                         gnome_vfs_uri_unref (folder_uri);
89                 }
90                 gnome_vfs_uri_unref (uri);
91
92                 if (folder_uri == NULL)
93                         return FALSE;
94
95                 if ((result != GNOME_VFS_OK) ||
96                     (!((folder_info->permissions & GNOME_VFS_PERM_ACCESS_WRITABLE) ||
97                        (folder_info->permissions & GNOME_VFS_PERM_USER_WRITE)))) {
98
99                         gnome_vfs_file_info_unref (folder_info);
100                         return FALSE;
101                 }
102                 gnome_vfs_file_info_unref (folder_info);
103         }
104         return TRUE;
105 }
106
107 gboolean
108 modest_utils_file_exists (const gchar *filename)
109 {
110         gboolean result = FALSE;
111         gchar *path;
112
113         g_return_val_if_fail (filename, FALSE);
114
115         path = strstr (filename, "file://");
116         if (!path)
117                 path = (gchar *) filename;
118         else
119                 path = (gchar *) filename + strlen ("file://");
120
121         if (g_access (path, F_OK) == 0)
122                 result = TRUE;
123
124         return result;
125 }
126
127 TnyFsStream *
128 modest_utils_create_temp_stream (const gchar *orig_name, const gchar *hash_base, gchar **path)
129 {
130         gint fd;
131         gchar *filepath = NULL;
132         gchar *tmpdir;
133         guint hash_number;
134
135         /* hmmm... maybe we need a modest_text_utils_validate_file_name? */
136         g_return_val_if_fail (orig_name && strlen(orig_name) != 0, NULL);
137
138         if (strlen(orig_name) > 200) {
139                 g_warning ("%s: filename too long ('%s')",
140                            __FUNCTION__, orig_name);
141                 return NULL;
142         }
143
144         if (g_strstr_len (orig_name, strlen (orig_name), "/") != NULL) {
145                 g_warning ("%s: filename contains '/' character(s) (%s)",
146                            __FUNCTION__, orig_name);
147                 return NULL;
148         }
149
150         /* make a random subdir under /tmp or /var/tmp */
151         if (hash_base != NULL) {
152                 hash_number = g_str_hash (hash_base);
153         } else {
154                 hash_number = (guint) random ();
155         }
156         tmpdir = g_strdup_printf ("%s/%u", g_get_tmp_dir (), hash_number);
157         if ((g_access (tmpdir, R_OK) == -1) && (g_mkdir (tmpdir, 0755) == -1)) {
158                 g_warning ("%s: failed to create dir '%s': %s",
159                            __FUNCTION__, tmpdir, g_strerror(errno));
160                 g_free (tmpdir);
161                 return NULL;
162         }
163
164         filepath = g_build_filename (tmpdir, orig_name, NULL);
165
166         /* if file exists, first we try to remove it */
167         if (g_access (filepath, F_OK) == 0)
168                 g_unlink (filepath);
169
170         /* don't overwrite if it already exists, even if it is writable */
171         if (g_access (filepath, F_OK) == 0) {
172                 if (path!=NULL) {
173                         *path = filepath;
174                 } else {
175                         g_free (filepath);
176                 }
177                 g_free (tmpdir);
178                 return NULL;
179         } else {
180                 /* try to write the file there */
181                 fd = g_open (filepath, O_CREAT|O_WRONLY|O_TRUNC, 0644);
182                 if (fd == -1) {
183                         g_warning ("%s: failed to create '%s': %s",
184                                         __FUNCTION__, filepath, g_strerror(errno));
185                         g_free (filepath);
186                         g_free (tmpdir);
187                         return NULL;
188                 }
189         }
190
191         g_free (tmpdir);
192
193         if (path)
194                 *path = filepath;
195         else
196                 g_free (filepath);
197
198         return TNY_FS_STREAM (tny_fs_stream_new (fd));
199 }
200
201 typedef struct 
202 {
203         GList **result;
204         GtkWidget* dialog;
205         GtkWidget* progress;
206 } ModestGetSupportedAuthInfo;
207
208 static gboolean
209 on_idle_secure_auth_finished (gpointer user_data)
210 {
211         /* Operation has finished, close the dialog. Control continues after
212          * gtk_dialog_run in modest_utils_get_supported_secure_authentication_methods() */
213         gdk_threads_enter(); /* CHECKED */
214         gtk_dialog_response (GTK_DIALOG (user_data), GTK_RESPONSE_ACCEPT);
215         gdk_threads_leave(); /* CHECKED */
216
217         return FALSE;
218 }
219
220 static void
221 on_camel_account_get_supported_secure_authentication (TnyCamelAccount *self,
222                                                       gboolean cancelled,
223                                                       TnyList *auth_types,
224                                                       GError *err,
225                                                       gpointer user_data)
226 {
227         ModestPairList *pairs;
228         GList *result;
229         ModestProtocolRegistry *protocol_registry;
230         ModestGetSupportedAuthInfo *info = (ModestGetSupportedAuthInfo*)user_data;
231         TnyIterator* iter;
232
233         g_return_if_fail (user_data);
234         g_return_if_fail (TNY_IS_CAMEL_ACCOUNT(self));
235         g_return_if_fail (TNY_IS_LIST(auth_types));
236
237         info = (ModestGetSupportedAuthInfo *) user_data;
238
239         /* Free everything if the actual action was canceled */
240         if (cancelled) {
241                 g_debug ("%s: operation canceled\n", __FUNCTION__);
242                 goto close_dialog;
243         }
244
245         if (err) {
246                 g_debug ("%s: error getting the supported auth methods\n", __FUNCTION__);
247                 goto close_dialog;
248         }
249
250         if (!auth_types) {
251                 g_debug ("%s: auth_types is NULL.\n", __FUNCTION__);
252                 goto close_dialog;
253         }
254
255         if (tny_list_get_length(auth_types) == 0) {
256                 g_debug ("%s: auth_types is an empty TnyList.\n", __FUNCTION__);
257                 goto close_dialog;
258         }
259
260         protocol_registry = modest_runtime_get_protocol_registry ();
261         pairs = modest_protocol_registry_get_pair_list_by_tag (protocol_registry, MODEST_PROTOCOL_REGISTRY_AUTH_PROTOCOLS);
262
263         /* Get the enum value for the strings: */
264         result = NULL;
265         iter = tny_list_create_iterator(auth_types);
266         while (!tny_iterator_is_done(iter)) {
267                 TnyPair *pair;
268                 const gchar *auth_name;
269                 ModestProtocolType protocol_type;
270
271                 pair = TNY_PAIR(tny_iterator_get_current(iter));
272                 auth_name = NULL;
273                 if (pair) {
274                         auth_name = tny_pair_get_name(pair);
275                         g_object_unref (pair);
276                         pair = NULL;
277                 }
278
279                 g_debug ("%s: auth_name=%s\n", __FUNCTION__, auth_name);
280
281                 protocol_type = modest_protocol_get_type_id (modest_protocol_registry_get_protocol_by_name (protocol_registry,
282                                                                                                             MODEST_PROTOCOL_REGISTRY_AUTH_PROTOCOLS,
283                                                                                                             auth_name));
284
285                 if (modest_protocol_registry_protocol_type_is_secure (protocol_registry, protocol_type))
286                         result = g_list_prepend(result, GINT_TO_POINTER(protocol_type));
287
288                 tny_iterator_next(iter);
289         }
290         g_object_unref (iter);
291
292         modest_pair_list_free (pairs);
293         *(info->result) = result;
294
295  close_dialog:
296         /* Close the dialog in a main thread */
297         g_idle_add(on_idle_secure_auth_finished, info->dialog);
298
299         /* Free the info */
300         g_slice_free (ModestGetSupportedAuthInfo, info);
301 }
302
303 typedef struct {
304         GtkWidget *progress;
305         gboolean not_finished;
306 } KeepPulsing;
307
308 static gboolean
309 keep_pulsing (gpointer user_data)
310 {
311         KeepPulsing *info = (KeepPulsing *) user_data;
312
313         if (!info->not_finished) {
314                 g_slice_free (KeepPulsing, info);
315                 return FALSE;
316         }
317
318         gtk_progress_bar_pulse (GTK_PROGRESS_BAR (info->progress));
319         return TRUE;
320 }
321
322 GList*
323 modest_utils_get_supported_secure_authentication_methods (ModestProtocolType protocol_type,
324                                                           const gchar* hostname,
325                                                           gint port,
326                                                           const gchar* username,
327                                                           GtkWindow *parent_window,
328                                                           GError** error)
329 {
330         TnyAccount * tny_account = NULL;
331         ModestProtocolRegistry *protocol_registry;
332         GtkWidget *dialog;
333         gint retval;
334         ModestTnyAccountStore *account_store;
335         TnySessionCamel *session = NULL;
336         ModestProtocol *protocol = NULL;
337         GList *result = NULL;
338         GtkWidget *progress;
339
340         g_return_val_if_fail (protocol_type != MODEST_PROTOCOL_REGISTRY_TYPE_INVALID, NULL);
341
342         protocol_registry = modest_runtime_get_protocol_registry ();
343
344         /* We need a connection to get the capabilities; */
345         if (!modest_platform_connect_and_wait (GTK_WINDOW (parent_window), NULL))
346                 return NULL;
347
348         /* Create a TnyCamelAccount so we can use 
349          * tny_camel_account_get_supported_secure_authentication(): */
350         protocol = modest_protocol_registry_get_protocol_by_type (protocol_registry, protocol_type);
351         tny_account = NULL;
352         if (MODEST_IS_ACCOUNT_PROTOCOL (protocol)) {
353                 tny_account = modest_account_protocol_create_account (MODEST_ACCOUNT_PROTOCOL (protocol));
354         }
355
356         if (!tny_account) {
357                 g_printerr ("%s could not create tny account.", __FUNCTION__);
358                 return NULL;
359         }
360
361         /* Set proto, so that the prepare_func() vfunc will work when
362          * we call set_session(): */
363         protocol = modest_protocol_registry_get_protocol_by_type (protocol_registry, protocol_type);
364         tny_account_set_id (tny_account, "temp_account");
365         tny_account_set_proto (tny_account, modest_protocol_get_name (protocol));
366         tny_account_set_hostname (tny_account, hostname);
367         tny_account_set_user (tny_account, username);
368
369         if(port > 0)
370                 tny_account_set_port (tny_account, port);
371
372         /* Set the session for the account, so we can use it: */
373         account_store = modest_runtime_get_account_store ();
374         session = modest_tny_account_store_get_session (TNY_ACCOUNT_STORE (account_store));
375         g_return_val_if_fail (session, NULL);
376         tny_camel_account_set_session (TNY_CAMEL_ACCOUNT(tny_account), session);
377
378         dialog = gtk_dialog_new_with_buttons(" ",
379                                              parent_window,
380                                              GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
381                                              _("mcen_bd_dialog_cancel"),
382                                              GTK_RESPONSE_REJECT,
383                                              NULL);
384
385         /* Ask camel to ask the server, asynchronously: */
386         ModestGetSupportedAuthInfo *info = g_slice_new (ModestGetSupportedAuthInfo);
387         info->result = &result;
388         info->dialog = dialog;
389
390         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(info->dialog)->vbox),
391                           gtk_label_new(_("emev_ni_checking_supported_auth_methods")));
392         progress = gtk_progress_bar_new();
393         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(info->dialog)->vbox), progress);
394         gtk_widget_show_all(info->dialog);
395
396         KeepPulsing *pi = g_slice_new (KeepPulsing);
397         pi->progress = progress;
398         pi->not_finished = TRUE;
399
400         /* Starts the pulsing of the progressbar */
401         g_timeout_add (500, keep_pulsing, pi);
402
403         tny_camel_account_get_supported_secure_authentication (TNY_CAMEL_ACCOUNT (tny_account),
404                                                                on_camel_account_get_supported_secure_authentication,
405                                                                NULL,
406                                                                info);
407
408         retval = gtk_dialog_run (GTK_DIALOG (info->dialog));
409
410         pi->not_finished = FALSE;
411         /* pi is freed in the timeout itself to avoid a GCond here */
412
413         gtk_widget_destroy(dialog);
414
415         /* Frees */
416         tny_account_cancel (tny_account);
417         g_object_unref (tny_account);
418
419         return result;
420 }
421
422 void
423 modest_utils_show_dialog_and_forget (GtkWidget *parent_window,
424                                      GtkDialog *dialog)
425 {
426         g_return_if_fail (GTK_IS_DIALOG(dialog));
427
428 #ifdef MODEST_TOOLKIT_GTK
429         if (GTK_IS_WINDOW (parent_window)) {
430                 gtk_window_set_transient_for (GTK_WINDOW (dialog), parent_window);
431         } else {
432                 ModestWindowMgr *window_mgr;
433                 GtkWidget *shell;
434
435                 window_mgr = modest_runtime_get_window_mgr ();
436                 shell  = modest_gtk_window_mgr_get_shell (MODEST_GTK_WINDOW_MGR (window_mgr));
437                 gtk_window_set_transient_for (GTK_WINDOW (dialog), GTK_WINDOW (shell));
438         }
439 #else
440         g_return_if_fail (GTK_IS_WINDOW(parent_window));
441         gtk_window_set_transient_for (GTK_WINDOW (dialog), parent_window);
442 #endif
443
444         /* Destroy the dialog when it is closed: */
445         g_signal_connect_swapped (dialog,
446                                   "response",
447                                   G_CALLBACK (gtk_widget_destroy),
448                                   dialog);
449
450         gtk_widget_show (GTK_WIDGET (dialog));
451 }
452
453 void
454 modest_utils_toggle_action_set_active_block_notify (GtkToggleAction *action, gboolean value)
455 {
456         GSList *proxies = NULL;
457
458         g_return_if_fail (GTK_IS_TOGGLE_ACTION (action));
459
460         for (proxies = gtk_action_get_proxies (GTK_ACTION (action));
461              proxies != NULL; proxies = g_slist_next (proxies)) {
462                 GtkWidget *widget = (GtkWidget *) proxies->data;
463                 gtk_action_block_activate_from (GTK_ACTION (action), widget);
464         }
465
466         gtk_toggle_action_set_active (action, value);
467
468         for (proxies = gtk_action_get_proxies (GTK_ACTION (action));
469              proxies != NULL; proxies = g_slist_next (proxies)) {
470                 GtkWidget *widget = (GtkWidget *) proxies->data;
471                 gtk_action_unblock_activate_from (GTK_ACTION (action), widget);
472         }
473
474 }
475
476
477 gint 
478 modest_list_index (TnyList *list, GObject *object)
479 {
480         TnyIterator *iter;
481         gint index = 0;
482
483         g_return_val_if_fail (TNY_IS_LIST(list), -1);
484         g_return_val_if_fail (G_IS_OBJECT(object), -1);
485         
486         iter = tny_list_create_iterator (list);
487         while (!tny_iterator_is_done (iter)) {
488                 GObject *current = tny_iterator_get_current (iter);
489
490                 g_object_unref (current);
491                 if (current == object)
492                         break;
493
494                 tny_iterator_next (iter);
495                 index++;
496         }
497
498         if (tny_iterator_is_done (iter))
499                 index = -1;
500         g_object_unref (iter);
501         return index;
502 }
503
504 guint64 
505 modest_utils_get_available_space (const gchar *maildir_path)
506 {
507         gchar *folder;
508         gchar *uri_string;
509         GnomeVFSURI *uri;
510         GnomeVFSFileSize size;
511
512         folder = modest_local_folder_info_get_maildir_path (maildir_path);
513         uri_string = gnome_vfs_get_uri_from_local_path (folder);
514         uri = gnome_vfs_uri_new (uri_string);
515         g_free (folder);
516         g_free (uri_string);
517
518         if (uri) {
519                 if (gnome_vfs_get_volume_free_space (uri, &size) != GNOME_VFS_OK)
520                         size = 0;
521                 gnome_vfs_uri_unref (uri);
522         } else {
523                 size = 0;
524         }
525
526         return (guint64) size;
527 }
528 static void
529 on_destroy_dialog (GtkDialog *dialog)
530 {
531         gtk_widget_destroy (GTK_WIDGET(dialog));
532         if (gtk_events_pending ())
533                 gtk_main_iteration ();
534 }
535
536 static guint
537 checked_modest_sort_criterium_view_add_sort_key (ModestSortCriteriumView *view, const gchar* key, guint max)
538 {
539         gint sort_key;
540         
541         g_return_val_if_fail (view && MODEST_IS_SORT_CRITERIUM_VIEW(view), 0);
542         g_return_val_if_fail (key, 0);
543         
544         sort_key = modest_sort_criterium_view_add_sort_key (view, key);
545         if (sort_key < 0 || sort_key >= max) {
546                 g_warning ("%s: out of range (%d) for %s", __FUNCTION__, sort_key, key);
547                 return 0;
548         } else
549                 return (guint)sort_key; 
550 }
551
552 static void
553 launch_sort_headers_dialog (GtkWindow *parent_window,
554                             GtkDialog *dialog)
555 {
556         ModestHeaderView *header_view = NULL;
557         GList *cols = NULL;
558         GtkSortType sort_type;
559         gint sort_key;
560         gint default_key = 0;
561         gint result;
562         gboolean outgoing = FALSE;
563         gint current_sort_colid = -1;
564         GtkSortType current_sort_type;
565         gint attachments_sort_id;
566         gint priority_sort_id;
567         GtkTreeSortable *sortable;
568
569         /* Get header window */
570         if (MODEST_IS_HEADER_WINDOW (parent_window)) {
571                 header_view = MODEST_HEADER_VIEW (modest_header_window_get_header_view (MODEST_HEADER_WINDOW (parent_window)));
572         }
573         if (!header_view)
574                 return;
575
576         /* Add sorting keys */
577         cols = modest_header_view_get_columns (header_view);
578         if (cols == NULL) 
579                 return;
580 #define SORT_ID_NUM 6
581         int sort_model_ids[SORT_ID_NUM];
582         int sort_ids[SORT_ID_NUM];
583
584         outgoing = (GPOINTER_TO_INT (g_object_get_data(G_OBJECT(cols->data), MODEST_HEADER_VIEW_COLUMN))==
585                     MODEST_HEADER_VIEW_COLUMN_COMPACT_HEADER_OUT);
586
587         sort_key = checked_modest_sort_criterium_view_add_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), _("mcen_li_sort_sender_recipient"),
588                                                                     SORT_ID_NUM);
589         if (outgoing) {
590                 sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_TO_COLUMN;
591                 sort_ids[sort_key] = MODEST_HEADER_VIEW_COLUMN_COMPACT_HEADER_OUT;
592         } else {
593                 sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_FROM_COLUMN;
594                 sort_ids[sort_key] = MODEST_HEADER_VIEW_COLUMN_COMPACT_HEADER_IN;
595         }
596
597         sort_key = checked_modest_sort_criterium_view_add_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), _("mcen_li_sort_date"),
598                                                             SORT_ID_NUM);
599         if (outgoing) {
600                 sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_DATE_SENT_TIME_T_COLUMN;
601                 sort_ids[sort_key] = MODEST_HEADER_VIEW_COLUMN_COMPACT_SENT_DATE;
602         } else {
603                 sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_DATE_RECEIVED_TIME_T_COLUMN;
604                 sort_ids[sort_key] = MODEST_HEADER_VIEW_COLUMN_COMPACT_RECEIVED_DATE;
605         }
606         default_key = sort_key;
607
608         sort_key = checked_modest_sort_criterium_view_add_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), _("mcen_li_sort_subject"),
609                                                                     SORT_ID_NUM);
610         sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_SUBJECT_COLUMN;
611         if (outgoing)
612                 sort_ids[sort_key] = MODEST_HEADER_VIEW_COLUMN_COMPACT_HEADER_OUT;
613         else
614                 sort_ids[sort_key] = MODEST_HEADER_VIEW_COLUMN_COMPACT_HEADER_IN;
615
616         sort_key = checked_modest_sort_criterium_view_add_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), _("mcen_li_sort_attachment"),
617                                                                     SORT_ID_NUM);
618         sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_FLAGS_COLUMN;
619         sort_ids[sort_key] = TNY_HEADER_FLAG_ATTACHMENTS;
620         attachments_sort_id = sort_key;
621
622         sort_key = checked_modest_sort_criterium_view_add_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), _("mcen_li_sort_size"),
623                                                                     SORT_ID_NUM);
624         sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_MESSAGE_SIZE_COLUMN;
625         sort_ids[sort_key] = 0;
626
627         sort_key = checked_modest_sort_criterium_view_add_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), _("mcen_li_sort_priority"),
628                                                                     SORT_ID_NUM);
629         sort_model_ids[sort_key] = TNY_GTK_HEADER_LIST_MODEL_FLAGS_COLUMN;
630         sort_ids[sort_key] = TNY_HEADER_FLAG_PRIORITY_MASK;
631         priority_sort_id = sort_key;
632         
633         sortable = GTK_TREE_SORTABLE (gtk_tree_view_get_model (GTK_TREE_VIEW (header_view)));
634         /* Launch dialogs */
635         if (!gtk_tree_sortable_get_sort_column_id (sortable,
636                                                    &current_sort_colid, &current_sort_type)) {
637                 modest_sort_criterium_view_set_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), default_key);
638                 modest_sort_criterium_view_set_sort_order (MODEST_SORT_CRITERIUM_VIEW (dialog), GTK_SORT_DESCENDING);
639         } else {
640                 modest_sort_criterium_view_set_sort_order (MODEST_SORT_CRITERIUM_VIEW (dialog), current_sort_type);
641                 if (current_sort_colid == TNY_GTK_HEADER_LIST_MODEL_FLAGS_COLUMN) {
642                         gpointer flags_sort_type_pointer;
643                         flags_sort_type_pointer = g_object_get_data (G_OBJECT (cols->data), MODEST_HEADER_VIEW_FLAG_SORT);
644                         if (GPOINTER_TO_INT (flags_sort_type_pointer) == TNY_HEADER_FLAG_PRIORITY_MASK)
645                                 modest_sort_criterium_view_set_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), priority_sort_id);
646                         else
647                                 modest_sort_criterium_view_set_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), attachments_sort_id);
648                 } else {
649                         gint current_sort_keyid = 0;
650                         while (current_sort_keyid < SORT_ID_NUM) {
651                                 if (sort_model_ids[current_sort_keyid] == current_sort_colid)
652                                         break;
653                                 else 
654                                         current_sort_keyid++;
655                         }
656                         modest_sort_criterium_view_set_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog), current_sort_keyid);
657                 }
658         }
659
660         result = gtk_dialog_run (GTK_DIALOG (dialog));
661         if (result == GTK_RESPONSE_OK) {
662                 sort_key = modest_sort_criterium_view_get_sort_key (MODEST_SORT_CRITERIUM_VIEW (dialog));
663                 if (sort_key < 0 || sort_key > SORT_ID_NUM -1) {
664                         g_warning ("%s: out of range (%d)", __FUNCTION__, sort_key);
665                         sort_key = 0;
666                 }
667
668                 sort_type = modest_sort_criterium_view_get_sort_order (MODEST_SORT_CRITERIUM_VIEW (dialog));
669                 if (sort_model_ids[sort_key] == TNY_GTK_HEADER_LIST_MODEL_FLAGS_COLUMN) {
670                         g_object_set_data (G_OBJECT(cols->data), MODEST_HEADER_VIEW_FLAG_SORT,
671                                            GINT_TO_POINTER (sort_ids[sort_key]));
672                         /* This is a hack to make it resort rows always when flag fields are
673                          * selected. If we do not do this, changing sort field from priority to
674                          * attachments does not work */
675                         modest_header_view_sort_by_column_id (header_view, 0, sort_type);
676                 } else {
677                         gtk_tree_view_column_set_sort_column_id (GTK_TREE_VIEW_COLUMN (cols->data), 
678                                                                  sort_model_ids[sort_key]);
679                 }
680
681                 modest_header_view_sort_by_column_id (header_view, sort_model_ids[sort_key], sort_type);
682                 gtk_tree_sortable_sort_column_changed (sortable);
683         }
684
685         modest_widget_memory_save (modest_runtime_get_conf (),
686                                    G_OBJECT (header_view), MODEST_CONF_HEADER_VIEW_KEY);
687         
688         /* free */
689         g_list_free(cols);      
690 }
691
692 void
693 modest_utils_run_sort_dialog (GtkWindow *parent_window,
694                               ModestSortDialogType type)
695 {
696         GtkWidget *dialog = NULL;
697
698         /* Build dialog */
699         dialog = modest_platform_create_sort_dialog (parent_window);
700         if (dialog == NULL)
701                 return;
702         modest_window_mgr_set_modal (modest_runtime_get_window_mgr (),
703                                      GTK_WINDOW (dialog), parent_window);
704
705         /* Fill sort keys */
706         switch (type) {
707         case MODEST_SORT_HEADERS:
708                 launch_sort_headers_dialog (parent_window, 
709                                             GTK_DIALOG(dialog));
710                 break;
711         }
712         
713         /* Free */
714         on_destroy_dialog (GTK_DIALOG(dialog));
715 }
716
717
718 gchar *
719 modest_images_cache_get_id (const gchar *account, const gchar *uri)
720 {
721         GnomeVFSURI *vfs_uri;
722         gchar *result;
723  
724         vfs_uri = gnome_vfs_uri_new (uri);
725         if (vfs_uri == NULL)
726                 return NULL;
727  
728         result = g_strdup_printf ("%s__%x", account, gnome_vfs_uri_hash (vfs_uri));
729         gnome_vfs_uri_unref (vfs_uri);
730  
731         return result;
732 }
733
734 gchar *
735 modest_utils_get_account_name_from_recipient (const gchar *from_header, gchar **mailbox)
736 {
737         gchar *account_name = NULL;
738         ModestAccountMgr *mgr = NULL;
739         GSList *accounts = NULL, *node = NULL;
740
741         if (mailbox)
742                 *mailbox = NULL;
743         g_return_val_if_fail (from_header, NULL);
744
745         mgr = modest_runtime_get_account_mgr ();
746         accounts = modest_account_mgr_account_names (mgr, TRUE);
747                 
748         for (node = accounts; node != NULL; node = g_slist_next (node)) {
749                 gchar *from;
750                 gchar *transport_account;
751
752                 if (!strcmp (from_header, node->data)) {
753                         account_name = g_strdup (node->data);
754                         break;
755                 }
756
757                 transport_account = modest_account_mgr_get_server_account_name (modest_runtime_get_account_mgr (),
758                                                                                 (const gchar *) node->data,
759                                                                                 TNY_ACCOUNT_TYPE_TRANSPORT);
760                 if (transport_account) {
761                         gchar *proto;
762                         proto = modest_account_mgr_get_string (mgr, transport_account, MODEST_ACCOUNT_PROTO, TRUE);
763
764                         if (proto != NULL) {
765                                 ModestProtocol *protocol = 
766                                         modest_protocol_registry_get_protocol_by_name (modest_runtime_get_protocol_registry (),
767                                                                                        MODEST_PROTOCOL_REGISTRY_TRANSPORT_PROTOCOLS,
768                                                                                        proto);
769                                 if (protocol && MODEST_IS_ACCOUNT_PROTOCOL (protocol)) {
770                                         ModestPairList *pair_list;
771                                         ModestPair *pair;
772                                         gchar *from_header_email =
773                                                 modest_text_utils_get_email_address (from_header);
774                                         pair_list = modest_account_protocol_get_from_list (MODEST_ACCOUNT_PROTOCOL (protocol),
775                                                                                            node->data);
776                                         
777                                         pair = modest_pair_list_find_by_first_as_string (pair_list, from_header_email);
778                                         if (pair != NULL) {
779                                                 account_name = g_strdup (node->data);
780                                                 if (mailbox)
781                                                         *mailbox = g_strdup (from_header_email);
782                                         }
783                                         
784                                         modest_pair_list_free (pair_list);
785                                         
786                                 }
787                                 g_free (proto);
788                         }
789                         g_free (transport_account);
790                 }
791                 if (mailbox && *mailbox)
792                         break;
793
794                 from = 
795                         modest_account_mgr_get_from_string (mgr, node->data, NULL);
796                         
797                 if (from) {
798                         gchar *from_email = 
799                                 modest_text_utils_get_email_address (from);
800                         gchar *from_header_email =
801                                 modest_text_utils_get_email_address (from_header);
802                                 
803                         if (from_email && from_header_email) {
804                                 if (!modest_text_utils_utf8_strcmp (from_header_email, from_email, TRUE)) {
805                                         account_name = g_strdup (node->data);
806                                         g_free (from);
807                                         g_free (from_email);
808                                         break;
809                                 }
810                         }
811                         g_free (from_email);
812                         g_free (from_header_email);
813                         g_free (from);
814                 }
815
816                         
817         }
818         g_slist_foreach (accounts, (GFunc) g_free, NULL);
819         g_slist_free (accounts);
820
821         return account_name;
822 }
823
824 void 
825 modest_utils_on_entry_invalid_character (ModestValidatingEntry *self, 
826                                          const gchar* character,
827                                          gpointer user_data)
828 {
829         gchar *message = NULL;
830         const gchar *show_char = NULL;
831
832         if (character)
833                 show_char = character;
834         else {
835                 show_char = "' '";
836         }
837         
838         message = g_strdup_printf (_CS("ckdg_ib_illegal_characters_entered"), show_char);
839         modest_platform_information_banner (GTK_WIDGET (self), NULL, message);
840         g_free (message);
841 }
842
843 FILE*
844 modest_utils_open_mcc_mapping_file (void)
845 {
846         FILE* result = NULL;
847         const gchar* path;
848
849         if (access (MODEST_OPERATOR_WIZARD_MCC_MAPPING, R_OK) == 0) {
850                 path = MODEST_OPERATOR_WIZARD_MCC_MAPPING;
851         } else if (access (MODEST_MCC_MAPPING, R_OK) == 0) {
852                 path = MODEST_MCC_MAPPING;
853         } else {
854                 g_warning ("%s: neither '%s' nor '%s' is a readable mapping file",
855                            __FUNCTION__, MODEST_OPERATOR_WIZARD_MCC_MAPPING, MODEST_MCC_MAPPING);
856                 return NULL;
857         }
858
859         result = fopen (path, "r");
860         if (!result) {
861                 g_warning ("%s: error opening mapping file '%s': %s",
862                            __FUNCTION__, path, strerror(errno));
863         }
864
865         return result;
866 }
867
868 /* each line is of the form:
869    xxx    logical_id
870
871   NOTE: this function is NOT re-entrant, the out-param country
872   are static strings that should NOT be freed. and will change when
873   calling this function again
874 */
875 static int
876 parse_mcc_mapping_line (const char* line,  char** country)
877 {
878         char mcc[4];  /* the mcc code, always 3 bytes*/
879         gchar *iter, *tab, *final;
880
881         if (!line) {
882                 *country = NULL;
883                 return 0;
884         }
885
886         /* Go to the first tab (Country separator) */
887         tab = g_utf8_strrchr (line, -1, '\t');
888         if (!tab)
889                 return 0;
890
891         *country = g_utf8_find_next_char (tab, NULL);
892
893         /* Replace by end of string. We need to use strlen, because
894            g_utf8_strrchr expects bytes and not UTF8 characters. File
895            lines end with \r\n */
896         final = g_utf8_strrchr (tab, strlen (tab) + 1, '\r');
897         if (G_LIKELY (final))
898                 *final = '\0';
899         else
900                 tab[strlen(tab) - 1] = '\0';
901
902         /* Get MCC code */
903         mcc[0] = g_utf8_get_char (line);
904         iter = g_utf8_find_next_char (line, NULL);
905         mcc[1] = g_utf8_get_char (iter);
906         iter = g_utf8_find_next_char (iter, NULL);
907         mcc[2] = g_utf8_get_char (iter);
908         mcc[3] = '\0';
909
910         return (int) strtol ((const char*)mcc, NULL, 10);
911 }
912
913 #define MCC_FILE_MAX_LINE_LEN 128 /* max length of a line in MCC file */
914
915 /** Note that the mcc_mapping file is installed 
916  * by the operator-wizard-settings package.
917  */
918 GtkTreeModel *
919 modest_utils_create_country_model (void)
920 {
921         GtkTreeModel *model;
922
923         model = GTK_TREE_MODEL (gtk_list_store_new (2,  G_TYPE_STRING, G_TYPE_INT));
924
925         return model;
926 }
927
928 void
929 modest_utils_fill_country_model (GtkTreeModel *model, gint *locale_mcc)
930 {
931         char line[MCC_FILE_MAX_LINE_LEN];
932         guint previous_mcc = 0;
933         gchar *territory;
934         GHashTable *country_hash;
935         FILE *file;
936
937         /* First we need to know our current region */
938         file = modest_utils_open_mcc_mapping_file ();
939         if (!file) {
940                 g_warning ("Could not open mcc_mapping file");
941                 return;
942         }
943
944         /* Get the territory specified for the current locale */
945         territory = nl_langinfo (_NL_IDENTIFICATION_TERRITORY);
946
947         setlocale (LC_MESSAGES, "en_GB");
948
949         while (fgets (line, MCC_FILE_MAX_LINE_LEN, file) != NULL) {
950                 int mcc;
951                 char *country = NULL;
952
953                 mcc = parse_mcc_mapping_line (line, &country);
954                 if (!country || mcc == 0) {
955                         g_warning ("%s: error parsing line: '%s'", __FUNCTION__, line);
956                         continue;
957                 }
958
959                 if (mcc == previous_mcc) {
960                         /* g_warning ("already seen: %s", line); */
961                         continue;
962                 }
963                 previous_mcc = mcc;
964
965                 if (!(*locale_mcc)) {
966                         gchar *translation = dgettext ("osso-countries", country);
967                         if (!g_utf8_collate (translation, territory))
968                                 *locale_mcc = mcc;
969                 }
970         }
971
972         setlocale (LC_MESSAGES, "");
973
974         /* Now we fill the model */
975         rewind (file);
976         country_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
977         while (fgets (line, MCC_FILE_MAX_LINE_LEN, file) != NULL) {
978
979                 int mcc;
980                 char *country = NULL;
981                 GtkTreeIter iter;
982                 const gchar *name_translated;
983
984                 mcc = parse_mcc_mapping_line (line, &country);
985                 if (!country || mcc == 0) {
986                         g_warning ("%s: error parsing line: '%s'", __FUNCTION__, line);
987                         continue;
988                 }
989
990                 if (mcc == previous_mcc ||
991                     g_hash_table_lookup (country_hash, country)) {
992                         g_debug ("already seen: '%s' %d", country, mcc);
993                         continue;
994                 }
995                 previous_mcc = mcc;
996
997                 g_hash_table_insert (country_hash, g_strdup (country), GINT_TO_POINTER (mcc));
998
999                 name_translated = dgettext ("osso-countries", country);
1000
1001                 /* Add the row to the model if we have translation for it */
1002                 if (g_utf8_collate (country, name_translated)) {
1003                         gtk_list_store_append (GTK_LIST_STORE (model), &iter);
1004                         gtk_list_store_set(GTK_LIST_STORE (model), &iter,
1005                                            MODEST_UTILS_COUNTRY_MODEL_COLUMN_MCC, mcc,
1006                                            MODEST_UTILS_COUNTRY_MODEL_COLUMN_NAME, name_translated,
1007                                            -1);
1008                 } else {
1009                         g_debug ("%s no translation for %s", __FUNCTION__, country);
1010                 }
1011         }
1012
1013
1014         g_hash_table_unref (country_hash);
1015         fclose (file);
1016
1017         /* Fallback to Finland */
1018         if (!(*locale_mcc))
1019                 *locale_mcc = 244;
1020
1021         /* Sort the items: */
1022         gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (model), 
1023                                               MODEST_UTILS_COUNTRY_MODEL_COLUMN_NAME, GTK_SORT_ASCENDING);
1024 }
1025
1026 GList *
1027 modest_utils_create_notification_list_from_header_list (TnyList *header_list)
1028 {
1029         GList *new_headers_list;
1030         TnyIterator *iter;
1031
1032         g_return_val_if_fail (TNY_IS_LIST (header_list), NULL);
1033         g_return_val_if_fail (tny_list_get_length (header_list) > 0, NULL);
1034
1035         new_headers_list = NULL;
1036         iter = tny_list_create_iterator (header_list);
1037         while (!tny_iterator_is_done (iter)) {
1038                 ModestMsgNotificationData *data;
1039                 TnyHeader *header;
1040                 TnyFolder *folder;
1041
1042                 header = (TnyHeader *) tny_iterator_get_current (iter);
1043                 if (header) {
1044                         folder = tny_header_get_folder (header);
1045
1046                         if (folder) {
1047                                 gchar *uri, *uid;
1048
1049                                 uid = tny_header_dup_uid (header);
1050                                 uri = g_strdup_printf ("%s/%s",
1051                                                        tny_folder_get_url_string (folder),
1052                                                        uid);
1053                                 g_free (uid);
1054
1055                                 /* Create data & add to list */
1056                                 data = g_slice_new0 (ModestMsgNotificationData);
1057                                 data->subject = tny_header_dup_subject (header);
1058                                 data->from = tny_header_dup_from (header);
1059                                 data->uri = uri;
1060
1061                                 new_headers_list = g_list_append (new_headers_list, data);
1062
1063                                 g_object_unref (folder);
1064                         }
1065                         g_object_unref (header);
1066                 }
1067                 tny_iterator_next (iter);
1068         }
1069         g_object_unref (iter);
1070
1071         return new_headers_list;
1072 }
1073
1074 static void
1075 free_notification_data (gpointer data,
1076                         gpointer user_data)
1077 {
1078         ModestMsgNotificationData *notification_data  = (ModestMsgNotificationData *) data;
1079
1080         g_free (notification_data->from);
1081         g_free (notification_data->subject);
1082         g_free (notification_data->uri);
1083
1084         g_slice_free (ModestMsgNotificationData, notification_data);
1085 }
1086
1087 void
1088 modest_utils_free_notification_list (GList *notification_list)
1089 {
1090         g_return_if_fail (g_list_length (notification_list) > 0);
1091
1092         g_list_foreach (notification_list, free_notification_data, NULL);
1093         g_list_free (notification_list);
1094 }
1095
1096 void
1097 modest_utils_flush_send_queue (const gchar *account_id)
1098 {
1099         TnyTransportAccount *account;
1100
1101         /* Get the transport account */
1102         account = (TnyTransportAccount *)
1103                 modest_tny_account_store_get_server_account (modest_runtime_get_account_store (),
1104                                                              account_id,
1105                                                              TNY_ACCOUNT_TYPE_TRANSPORT);
1106         if (account) {
1107                 ModestMailOperation *wakeup_op;
1108                 ModestTnySendQueue *send_queue = modest_runtime_get_send_queue (account, TRUE);
1109
1110                 /* Flush it! */
1111                 wakeup_op = modest_mail_operation_new (NULL);
1112                 modest_mail_operation_queue_add (modest_runtime_get_mail_operation_queue (),
1113                                                  wakeup_op);
1114                 modest_mail_operation_queue_wakeup (wakeup_op, send_queue);
1115
1116                 g_object_unref (account);
1117         }
1118 }