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