2007-07-23 Murray Cumming <murrayc@murrayc.com>
[modest] / src / maemo / modest-maemo-utils.c
1 /* Copyright (c) 2006, 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 #ifndef DBUS_API_SUBJECT_TO_CHANGE
31 #define DBUS_API_SUBJECT_TO_CHANGE
32 #endif /*DBUS_API_SUBJECT_TO_CHANGE*/
33
34 #include <dbus/dbus.h>
35 #include <dbus/dbus-glib-lowlevel.h>
36 #include <glib.h>
37 #include <modest-runtime.h>
38 #include <libgnomevfs/gnome-vfs.h>
39 #include <tny-fs-stream.h>
40 #include <tny-camel-account.h>
41 #include <tny-status.h>
42 #include <tny-camel-transport-account.h>
43 #include <tny-camel-imap-store-account.h>
44 #include <tny-camel-pop-store-account.h>
45 #include "modest-hildon-includes.h"
46
47 #include "modest-maemo-utils.h"
48
49 /*
50  * For getting and tracking the Bluetooth name
51  */
52 #define BTNAME_SERVICE                  "org.bluez"
53 #define BTNAME_REQUEST_IF               "org.bluez.Adapter"
54 #define BTNAME_SIGNAL_IF                "org.bluez.Adapter"
55 #define BTNAME_REQUEST_PATH             "/org/bluez/hci0"
56 #define BTNAME_SIGNAL_PATH              "/org/bluez/hci0"
57
58 #define BTNAME_REQ_GET                  "GetName"
59 #define BTNAME_SIG_CHANGED              "NameChanged"
60
61 #define BTNAME_MATCH_RULE "type='signal',interface='" BTNAME_SIGNAL_IF \
62                           "',member='" BTNAME_SIG_CHANGED "'"
63
64 GQuark modest_maemo_utils_get_supported_secure_authentication_error_quark (void)
65 {
66         return g_quark_from_static_string("modest-maemo-utils-get-supported-secure-authentication-error-quark");
67 }
68
69 GtkWidget*
70 modest_maemo_utils_menubar_to_menu (GtkUIManager *ui_manager)
71 {
72         GtkWidget *main_menu;
73         GtkWidget *menubar;
74         GList *iter;
75
76         g_return_val_if_fail (ui_manager, NULL);
77         
78         /* Create new main menu */
79         main_menu = gtk_menu_new();
80
81         /* Get the menubar from the UI manager */
82         menubar = gtk_ui_manager_get_widget (ui_manager, "/MenuBar");
83
84         iter = gtk_container_get_children (GTK_CONTAINER (menubar));
85         while (iter) {
86                 GtkWidget *menu;
87
88                 menu = GTK_WIDGET (iter->data);
89                 gtk_widget_reparent(menu, main_menu);
90
91                 iter = g_list_next (iter);
92         }
93         return main_menu;
94 }
95
96
97 static void
98 update_device_name_from_msg (DBusMessage *message)
99 {
100         DBusError error;
101         DBusMessageIter iter;
102
103         dbus_error_init (&error);
104
105         if (dbus_set_error_from_message (&error, message)) {
106                 g_printerr ("modest: failed to get bluetooth name: %s\n", error.message);
107                 dbus_error_free (&error);
108         } else {
109                 const gchar *device_name;
110                 if (!dbus_message_iter_init (message, &iter)) {
111                         g_printerr ("modest: message did not have argument\n");
112                         return;
113                 }
114                 dbus_message_iter_get_basic (&iter, &device_name);
115                 g_warning ("update device name: %s", device_name);
116                 modest_conf_set_string (modest_runtime_get_conf(),
117                                         MODEST_CONF_DEVICE_NAME, device_name,
118                                         NULL);
119         }
120 }
121
122
123 static void
124 on_device_name_received (DBusPendingCall *call, void *user_data)
125 {
126         DBusMessage *message;
127         
128         g_return_if_fail (dbus_pending_call_get_completed (call));
129         
130         message = dbus_pending_call_steal_reply (call);
131         if (!message) {
132                 g_printerr ("modest: no reply on device name query\n");
133                 return;
134         }
135
136         update_device_name_from_msg (message);
137         dbus_message_unref (message);
138 }
139
140
141 static DBusHandlerResult
142 handle_dbus_signal (DBusConnection *conn, DBusMessage *msg, gpointer data)
143 {
144         if (dbus_message_is_signal(msg, BTNAME_SIGNAL_IF, BTNAME_SIG_CHANGED))
145                 update_device_name_from_msg (msg);
146
147         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
148 }
149
150
151 static void
152 get_device_name_from_dbus ()
153 {
154         static DBusConnection *conn = NULL;
155         DBusMessage *request;
156         DBusError error;
157         DBusPendingCall *call = NULL;
158         
159         dbus_error_init (&error);
160         if (!conn) {
161                 conn = dbus_bus_get (DBUS_BUS_SYSTEM, &error);
162                 if (!conn) {
163                         g_printerr ("modest: cannot get on the dbus: %s: %s\n",
164                                     error.name, error.message);
165                         dbus_error_free (&error);
166                         return;
167                 }
168         }
169         
170         request = dbus_message_new_method_call (BTNAME_SERVICE, BTNAME_REQUEST_PATH,
171                                                 BTNAME_REQUEST_IF, BTNAME_REQ_GET);
172         if (!request) {
173                 /* should we free the connection? */
174                 g_printerr ("modest: dbus_message_new_method_call failed\n");
175                 return;
176         }
177         dbus_message_set_auto_start (request, TRUE);
178         if (dbus_connection_send_with_reply (conn, request, &call, -1)) {
179                 dbus_pending_call_set_notify (call, on_device_name_received,
180                                               NULL, NULL);
181                 dbus_pending_call_unref (call);
182         }
183         dbus_message_unref (request);
184         
185         dbus_connection_setup_with_g_main (conn, NULL);
186         dbus_bus_add_match (conn, BTNAME_MATCH_RULE, &error);
187         if (dbus_error_is_set(&error)) {
188                 g_printerr ("modest: dbus_bus_add_match failed: %s\n", error.message);
189                 dbus_error_free (&error);
190         }
191
192         if (!dbus_connection_add_filter(conn, handle_dbus_signal, NULL, NULL))
193                 g_printerr ("modest: dbus_connection_add_filter failed\n");
194 }
195
196
197 void
198 modest_maemo_utils_get_device_name (void)
199 {
200         get_device_name_from_dbus ();
201 }
202
203 gboolean 
204 modest_maemo_utils_folder_writable (const gchar *filename)
205 {
206         g_return_val_if_fail (filename, FALSE);
207
208         if (!filename)
209                 return FALSE;
210         
211         if (g_strncasecmp (filename, "obex", 4) != 0) {
212                 GnomeVFSFileInfo folder_info;
213                 gchar *folder;
214                 folder = g_path_get_dirname (filename);
215                 gnome_vfs_get_file_info (folder, &folder_info,
216                                          GNOME_VFS_FILE_INFO_GET_ACCESS_RIGHTS);
217                 g_free (folder);
218                 if (!((folder_info.permissions & GNOME_VFS_PERM_ACCESS_WRITABLE) ||
219                       (folder_info.permissions & GNOME_VFS_PERM_USER_WRITE))) {
220                         return FALSE;
221                 }
222         }
223         return TRUE;
224 }
225
226 gboolean 
227 modest_maemo_utils_file_exists (const gchar *filename)
228 {
229         GnomeVFSURI *uri = NULL;
230         gboolean result = FALSE;
231
232         uri = gnome_vfs_uri_new (filename);
233         if (uri) {
234                 result = gnome_vfs_uri_exists (uri);
235                 gnome_vfs_uri_unref (uri);
236         }
237         return result;
238 }
239
240 TnyFsStream *
241 modest_maemo_utils_create_temp_stream (const gchar *extension, gchar **path)
242 {
243         TnyStream *tmp_fs_stream = NULL;
244         gint fd;
245         gchar *filepath = NULL;
246         gchar *template = NULL;
247
248         if (extension != NULL)
249                 template = g_strdup_printf ("XXXXXX.%s", extension);
250
251         fd = g_file_open_tmp (template, &filepath, NULL);
252         g_free (template);
253         if (path != NULL)
254                 *path = filepath;
255         if (fd == -1) {
256                 g_message ("TODO BANNER: Error saving stream");
257                 return NULL;
258         }
259         tmp_fs_stream = tny_fs_stream_new (fd);
260         
261         return TNY_FS_STREAM (tmp_fs_stream);
262 }
263
264 typedef struct 
265 {
266         gboolean cancel;
267         GList *result;
268         GtkWidget* dialog;
269         GtkWidget* progress;
270         GError* error;
271 } ModestGetSupportedAuthInfo;
272
273 static void on_camel_account_get_supported_secure_authentication_status (
274         GObject *self, TnyStatus *status, gpointer user_data)
275 {
276         /*ModestGetSupportedAuthInfo* info = (ModestGetSupportedAuthInfo*) user_data;*/
277 }
278
279 static gboolean
280 on_idle_secure_auth_finished (gpointer user_data)
281 {
282         ModestGetSupportedAuthInfo *info = (ModestGetSupportedAuthInfo*)user_data;
283         /* Operation has finished, close the dialog. Control continues after
284          * gtk_dialog_run in modest_maemo_utils_get_supported_secure_authentication_methods() */
285         gdk_threads_enter();
286         gtk_dialog_response (GTK_DIALOG (info->dialog), GTK_RESPONSE_ACCEPT);
287         gdk_threads_leave();
288         return FALSE;
289 }
290
291 static void
292 on_camel_account_get_supported_secure_authentication (
293   TnyCamelAccount *self, gboolean cancelled,
294   TnyList *auth_types, GError **err, 
295   gpointer user_data)
296 {
297                 
298         ModestGetSupportedAuthInfo *info = (ModestGetSupportedAuthInfo*)user_data;
299         g_return_if_fail (info);
300
301         gdk_threads_enter();
302
303         /* Free everything if the actual action was canceled */
304         if (info->cancel)
305         {
306                 /* The operation was canceled and the ownership of the info given to us
307                  * so that we could still check the cancel flag. */
308                 g_slice_free (ModestGetSupportedAuthInfo, info);
309                 info = NULL;
310         }
311         else
312         {
313                 /* TODO: Why is this a pointer to a pointer? We are not supposed to
314                  * set it, are we? */
315                 if(err != NULL && *err != NULL)
316                 {
317                         if(info->error != NULL) g_error_free(info->error);
318                         info->error = g_error_copy(*err);
319                 }
320
321                 if (!auth_types) {
322                         printf ("DEBUG: %s: auth_types is NULL.\n", __FUNCTION__);
323                 }
324                 else
325                 {
326                         ModestPairList* pairs = modest_protocol_info_get_auth_protocol_pair_list ();
327   
328                         /* Get the enum value for the strings: */
329                         GList *result = NULL;
330                         TnyIterator* iter = tny_list_create_iterator(auth_types);
331                         while (!tny_iterator_is_done(iter)) {
332                                 TnyPair *pair = TNY_PAIR(tny_iterator_get_current(iter));
333                                 const gchar *auth_name = NULL;
334                                 if (pair) {
335                                         auth_name = tny_pair_get_name(pair);
336                                         g_object_unref (pair);
337                                         pair = NULL;
338                                 }
339
340                                 printf("DEBUG: %s: auth_name=%s\n", __FUNCTION__, auth_name);
341                                 ModestPair *matching = modest_pair_list_find_by_first_as_string (pairs, 
342                                         auth_name);
343                                 if (matching)
344                                 {
345                                         result = g_list_append (result, GINT_TO_POINTER((ModestConnectionProtocol)matching->first));
346                                 }
347                                 tny_iterator_next(iter);
348                         }
349         
350                         g_object_unref(auth_types);
351
352                         modest_pair_list_free (pairs);
353         
354                         info->result = result;
355                 }
356
357                 printf("DEBUG: finished\n");
358
359                 /* Close the dialog in a main thread */
360                 g_idle_add(on_idle_secure_auth_finished, info);
361         }
362
363         gdk_threads_leave();
364 }
365
366 static void on_secure_auth_cancel(GtkWidget* dialog, int response, gpointer user_data)
367 {
368         if(response == GTK_RESPONSE_REJECT || response == GTK_RESPONSE_DELETE_EVENT)
369         {
370                 ModestGetSupportedAuthInfo *info = (ModestGetSupportedAuthInfo*)user_data;
371                 g_return_if_fail(info);
372                 /* This gives the ownership of the info to the worker thread. */
373                 info->result = NULL;
374                 info->cancel = TRUE;
375         }
376 }
377
378 GList* modest_maemo_utils_get_supported_secure_authentication_methods (ModestTransportStoreProtocol proto, 
379         const gchar* hostname, gint port, const gchar* username, GtkWindow *parent_window, GError** error)
380 {
381         g_return_val_if_fail (proto != MODEST_PROTOCOL_TRANSPORT_STORE_UNKNOWN, NULL);
382         
383         /*
384         result = g_list_append (result, GINT_TO_POINTER (MODEST_PROTOCOL_AUTH_CRAMMD5));
385         */
386         
387         /* Create a TnyCamelAccount so we can use 
388          * tny_camel_account_get_supported_secure_authentication(): */
389         TnyAccount * tny_account = NULL;
390         switch (proto) {
391         case MODEST_PROTOCOL_TRANSPORT_SENDMAIL:
392         case MODEST_PROTOCOL_TRANSPORT_SMTP:
393                 tny_account = TNY_ACCOUNT(tny_camel_transport_account_new ()); break;
394         case MODEST_PROTOCOL_STORE_POP:
395                 tny_account = TNY_ACCOUNT(tny_camel_pop_store_account_new ()); break;
396         case MODEST_PROTOCOL_STORE_IMAP:
397                 tny_account = TNY_ACCOUNT(tny_camel_imap_store_account_new ()); break;
398         case MODEST_PROTOCOL_STORE_MAILDIR:
399         case MODEST_PROTOCOL_STORE_MBOX:
400                 tny_account = TNY_ACCOUNT(tny_camel_store_account_new()); break;
401         default:
402                 tny_account = NULL;
403         }
404
405         /* TODO: Handle connection requests. */
406         
407         if (!tny_account) {
408                 g_printerr ("%s could not create tny account.", __FUNCTION__);
409                 return NULL;
410         }
411         
412         /* Set proto, so that the prepare_func() vfunc will work when we call 
413          * set_session(): */
414          /* TODO: Why isn't this done in account_new()? */
415         tny_account_set_proto (tny_account,
416                                modest_protocol_info_get_transport_store_protocol_name(proto));
417
418         tny_account_set_hostname (tny_account, hostname);
419         /* Required for POP, at least */
420         tny_account_set_user (tny_account, username);
421                                
422         /* Set the session for the account, so we can use it: */
423         ModestTnyAccountStore *account_store = modest_runtime_get_account_store ();
424         TnySessionCamel *session = 
425                 modest_tny_account_store_get_session (TNY_ACCOUNT_STORE (account_store));
426         g_return_val_if_fail (session, NULL);
427         tny_camel_account_set_session (TNY_CAMEL_ACCOUNT(tny_account), session);
428         
429         if(port > 0)
430                 tny_account_set_port (tny_account, port);
431                 
432
433         /* Ask camel to ask the server, asynchronously: */
434         ModestGetSupportedAuthInfo *info = g_slice_new (ModestGetSupportedAuthInfo);
435         info->result = NULL;
436         info->cancel = FALSE;
437         info->error = NULL;
438         info->progress = gtk_progress_bar_new();
439         info->dialog = gtk_dialog_new_with_buttons(_("Authentication"),
440                                                    parent_window, GTK_DIALOG_MODAL,
441                                                    GTK_STOCK_CANCEL,
442                                                    GTK_RESPONSE_REJECT,
443                                                    NULL);
444         //gtk_window_set_default_size(GTK_WINDOW(info->dialog), 300, 100);
445         
446         g_signal_connect(G_OBJECT(info->dialog), "response", G_CALLBACK(on_secure_auth_cancel), info);
447         
448         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(info->dialog)->vbox),
449                           gtk_label_new("Checking for supported authentication types..."));
450         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(info->dialog)->vbox), info->progress);
451         gtk_widget_show_all(info->dialog);
452         gtk_progress_bar_pulse(GTK_PROGRESS_BAR(info->progress));
453         
454         printf ("DEBUG: %s: STARTING.\n", __FUNCTION__);
455         tny_camel_account_get_supported_secure_authentication (
456                 TNY_CAMEL_ACCOUNT (tny_account),
457                 on_camel_account_get_supported_secure_authentication,
458                 on_camel_account_get_supported_secure_authentication_status,
459                 info);
460
461         gtk_dialog_run (GTK_DIALOG (info->dialog));
462         
463         gtk_widget_destroy(info->dialog);
464                 
465         GList *result = info->result;
466         if (!info->cancel)
467         {
468                 if(info->error != NULL)
469                         g_propagate_error(error, info->error);
470
471                 g_slice_free (ModestGetSupportedAuthInfo, info);
472                 info = NULL;
473         }
474         else
475         {
476                 // Tell the caller that the operation was canceled so it can
477                 // make a difference
478                 g_set_error(error,
479                             modest_maemo_utils_get_supported_secure_authentication_error_quark(),
480                             MODEST_MAEMO_UTILS_GET_SUPPORTED_SECURE_AUTHENTICATION_ERROR_CANCELED,
481                             "User has canceled query");
482         }
483
484         return result;
485 }
486
487 void
488 modest_maemo_utils_setup_images_filechooser (GtkFileChooser *chooser)
489 {
490         gchar *images_folder;
491         GtkFileFilter *file_filter;
492         GList *image_mimetypes_list;
493         GList *node;
494
495         g_return_if_fail (GTK_IS_FILE_CHOOSER (chooser));
496
497         /* Set the default folder to images folder */
498         images_folder = g_build_filename (g_get_home_dir (), 
499                                           MODEST_MAEMO_UTILS_MYDOCS_FOLDER,
500                                           MODEST_MAEMO_UTILS_DEFAULT_IMAGE_FOLDER, NULL);
501         gtk_file_chooser_set_current_folder (chooser, images_folder);
502         g_free (images_folder);
503
504         /* Set the images mime filter */
505         file_filter = gtk_file_filter_new ();
506 #ifdef MODEST_HAVE_HILDON0_WIDGETS
507         image_mimetypes_list = osso_mime_get_mime_types_for_category (OSSO_MIME_CATEGORY_IMAGES);
508 #else
509         image_mimetypes_list = hildon_mime_get_mime_types_for_category (HILDON_MIME_CATEGORY_IMAGES);
510 #endif
511         for (node = image_mimetypes_list; node != NULL; node = g_list_next (node)) {
512                 gtk_file_filter_add_mime_type (file_filter, node->data);
513         }
514         gtk_file_chooser_set_filter (chooser, file_filter);
515 #ifdef MODEST_HAVE_HILDON0_WIDGETS
516         osso_mime_types_list_free (image_mimetypes_list);
517 #else
518         hildon_mime_types_list_free (image_mimetypes_list);
519 #endif
520
521 }
522
523 static void
524 on_response (GtkDialog *dialog, gint response, gpointer user_data)
525 {
526         /* Just destroy the dialog: */
527         gtk_widget_destroy (GTK_WIDGET (dialog));
528 }
529
530 void
531 modest_maemo_show_information_note_and_forget (GtkWindow *parent_window, const gchar* message)
532 {
533         GtkDialog *dialog = GTK_DIALOG (hildon_note_new_information (parent_window, message));
534         
535         /* Destroy the dialog when it is closed: */
536         g_signal_connect (G_OBJECT (dialog), "response", G_CALLBACK (on_response), NULL);
537         gtk_widget_show (GTK_WIDGET (dialog));
538 }
539
540 #if 0
541 static void
542 on_hide (GtkDialog *dialog, gpointer user_data)
543 {
544         /* Just destroy the dialog: */
545         gtk_widget_destroy (GTK_WIDGET (dialog));
546 }
547 #endif
548
549 void modest_maemo_show_dialog_and_forget (GtkWindow *parent_window, GtkDialog *dialog)
550 {
551         gtk_window_set_transient_for (GTK_WINDOW (dialog), parent_window);
552         
553         /* Destroy the dialog when it is closed: */
554         g_signal_connect (G_OBJECT (dialog), "response", G_CALLBACK (on_response), NULL);
555         gtk_widget_show (GTK_WIDGET (dialog));
556 }
557
558 void
559 modest_maemo_set_thumbable_scrollbar (GtkScrolledWindow *win, gboolean thumbable)
560 {
561         g_return_if_fail (GTK_IS_SCROLLED_WINDOW(win));
562 #ifdef MODEST_HAVE_HILDON1_WIDGETS              
563         hildon_helper_set_thumb_scrollbar (win, thumbable);
564 #endif /* MODEST_HAVE_HILDON1_WIDGETS */
565 }
566
567 void
568 modest_maemo_toggle_action_set_active_block_notify (GtkToggleAction *action, gboolean value)
569 {
570         GSList *proxies = NULL;
571
572         g_return_if_fail (GTK_IS_TOGGLE_ACTION (action));
573
574         for (proxies = gtk_action_get_proxies (GTK_ACTION (action));
575              proxies != NULL; proxies = g_slist_next (proxies)) {
576                 GtkWidget *widget = (GtkWidget *) proxies->data;
577                 gtk_action_block_activate_from (GTK_ACTION (action), widget);
578         }
579
580         gtk_toggle_action_set_active (action, value);
581
582         for (proxies = gtk_action_get_proxies (GTK_ACTION (action));
583              proxies != NULL; proxies = g_slist_next (proxies)) {
584                 GtkWidget *widget = (GtkWidget *) proxies->data;
585                 gtk_action_unblock_activate_from (GTK_ACTION (action), widget);
586         }
587
588 }