]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-ui-utils.c
UOA: Do not segfault when "Done" or "Cancel" button clicked but widget is not ready yet
[empathy.git] / libempathy-gtk / empathy-ui-utils.c
1 /*
2  * Copyright (C) 2002-2007 Imendio AB
3  * Copyright (C) 2007-2010 Collabora Ltd.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA  02110-1301  USA
19  *
20  * Authors: Mikael Hallendal <micke@imendio.com>
21  *          Richard Hult <richard@imendio.com>
22  *          Martyn Russell <martyn@imendio.com>
23  *          Xavier Claessens <xclaesse@gmail.com>
24  *          Jonny Lamb <jonny.lamb@collabora.co.uk>
25  *          Travis Reitter <travis.reitter@collabora.co.uk>
26  *
27  *          Part of this file is copied from GtkSourceView (gtksourceiter.c):
28  *          Paolo Maggi
29  *          Jeroen Zwartepoorte
30  */
31
32 #include "config.h"
33
34 #include <X11/Xatom.h>
35 #include <gdk/gdkx.h>
36 #include <glib/gi18n-lib.h>
37 #include <gio/gdesktopappinfo.h>
38
39 #include "empathy-ui-utils.h"
40 #include "empathy-images.h"
41 #include "empathy-live-search.h"
42
43 #define DEBUG_FLAG EMPATHY_DEBUG_OTHER
44 #include <libempathy/empathy-debug.h>
45 #include <libempathy/empathy-utils.h>
46 #include <libempathy/empathy-ft-factory.h>
47
48 void
49 empathy_gtk_init (void)
50 {
51   static gboolean initialized = FALSE;
52
53   if (initialized)
54     return;
55
56   empathy_init ();
57
58   gtk_icon_theme_append_search_path (gtk_icon_theme_get_default (),
59       PKGDATADIR G_DIR_SEPARATOR_S "icons");
60
61   /* Add icons from source dir if available */
62   if (g_getenv ("EMPATHY_SRCDIR") != NULL)
63     {
64       gchar *path;
65
66       path = g_build_filename (g_getenv ("EMPATHY_SRCDIR"), "data",
67           "icons", "local-copy", NULL);
68
69       if (g_file_test (path, G_FILE_TEST_EXISTS))
70         gtk_icon_theme_append_search_path (gtk_icon_theme_get_default (), path);
71
72       g_free (path);
73     }
74
75   initialized = TRUE;
76 }
77
78 static GtkBuilder *
79 builder_get_file_valist (const gchar *filename,
80     const gchar *first_object,
81     va_list args)
82 {
83   GtkBuilder *gui;
84   const gchar *name;
85   GObject **object_ptr;
86   GError *error = NULL;
87
88   DEBUG ("Loading file %s", filename);
89
90   gui = gtk_builder_new ();
91   gtk_builder_set_translation_domain (gui, GETTEXT_PACKAGE);
92
93   if (!gtk_builder_add_from_file (gui, filename, &error))
94     {
95       g_critical ("GtkBuilder Error (%s): %s",
96           filename, error->message);
97
98       g_clear_error (&error);
99       g_object_unref (gui);
100
101       /* we need to iterate and set all of the pointers to NULL */
102       for (name = first_object; name; name = va_arg (args, const gchar *))
103         {
104           object_ptr = va_arg (args, GObject**);
105
106           *object_ptr = NULL;
107         }
108
109       return NULL;
110     }
111
112   for (name = first_object; name; name = va_arg (args, const gchar *))
113     {
114       object_ptr = va_arg (args, GObject**);
115
116       *object_ptr = gtk_builder_get_object (gui, name);
117
118       if (!*object_ptr)
119         {
120           g_warning ("File is missing object '%s'.", name);
121           continue;
122         }
123     }
124
125   return gui;
126 }
127
128 GtkBuilder *
129 empathy_builder_get_file (const gchar *filename,
130     const gchar *first_object,
131     ...)
132 {
133   GtkBuilder *gui;
134   va_list args;
135
136   va_start (args, first_object);
137   gui = builder_get_file_valist (filename, first_object, args);
138   va_end (args);
139
140   return gui;
141 }
142
143 void
144 empathy_builder_connect (GtkBuilder *gui,
145     gpointer user_data,
146     const gchar *first_object,
147     ...)
148 {
149   va_list args;
150   const gchar *name;
151   const gchar *sig;
152   GObject *object;
153   GCallback callback;
154
155   va_start (args, first_object);
156   for (name = first_object; name; name = va_arg (args, const gchar *))
157     {
158       sig = va_arg (args, const gchar *);
159       callback = va_arg (args, GCallback);
160
161       object = gtk_builder_get_object (gui, name);
162       if (!object)
163         {
164           g_warning ("File is missing object '%s'.", name);
165           continue;
166         }
167
168       g_signal_connect (object, sig, callback, user_data);
169     }
170
171   va_end (args);
172 }
173
174 GtkWidget *
175 empathy_builder_unref_and_keep_widget (GtkBuilder *gui,
176     GtkWidget *widget)
177 {
178   /* On construction gui sinks the initial reference to widget. When gui
179    * is finalized it will drop its ref to widget. We take our own ref to
180    * prevent widget being finalised. The widget is forced to have a
181    * floating reference, like when it was initially unowned so that it can
182    * be used like any other GtkWidget. */
183
184   g_object_ref (widget);
185   g_object_force_floating (G_OBJECT (widget));
186   g_object_unref (gui);
187
188   return widget;
189 }
190
191 const gchar *
192 empathy_icon_name_for_presence (TpConnectionPresenceType presence)
193 {
194   switch (presence)
195     {
196       case TP_CONNECTION_PRESENCE_TYPE_AVAILABLE:
197         return EMPATHY_IMAGE_AVAILABLE;
198       case TP_CONNECTION_PRESENCE_TYPE_BUSY:
199         return EMPATHY_IMAGE_BUSY;
200       case TP_CONNECTION_PRESENCE_TYPE_AWAY:
201         return EMPATHY_IMAGE_AWAY;
202       case TP_CONNECTION_PRESENCE_TYPE_EXTENDED_AWAY:
203         if (gtk_icon_theme_has_icon (gtk_icon_theme_get_default (),
204                    EMPATHY_IMAGE_EXT_AWAY))
205           return EMPATHY_IMAGE_EXT_AWAY;
206
207         /* The 'extended-away' icon is not an official one so we fallback to
208          * idle if it's not implemented */
209         return EMPATHY_IMAGE_IDLE;
210       case TP_CONNECTION_PRESENCE_TYPE_HIDDEN:
211         if (gtk_icon_theme_has_icon (gtk_icon_theme_get_default (),
212                    EMPATHY_IMAGE_HIDDEN))
213           return EMPATHY_IMAGE_HIDDEN;
214
215         /* The 'hidden' icon is not an official one so we fallback to offline if
216          * it's not implemented */
217         return EMPATHY_IMAGE_OFFLINE;
218       case TP_CONNECTION_PRESENCE_TYPE_OFFLINE:
219       case TP_CONNECTION_PRESENCE_TYPE_ERROR:
220         return EMPATHY_IMAGE_OFFLINE;
221       case TP_CONNECTION_PRESENCE_TYPE_UNKNOWN:
222         return EMPATHY_IMAGE_PENDING;
223       case TP_CONNECTION_PRESENCE_TYPE_UNSET:
224       default:
225         return NULL;
226     }
227
228   return NULL;
229 }
230
231 const gchar *
232 empathy_icon_name_for_contact (EmpathyContact *contact)
233 {
234   TpConnectionPresenceType presence;
235
236   g_return_val_if_fail (EMPATHY_IS_CONTACT (contact),
237       EMPATHY_IMAGE_OFFLINE);
238
239   presence = empathy_contact_get_presence (contact);
240   return empathy_icon_name_for_presence (presence);
241 }
242
243 const gchar *
244 empathy_icon_name_for_individual (FolksIndividual *individual)
245 {
246   FolksPresenceType folks_presence;
247   TpConnectionPresenceType presence;
248
249   folks_presence = folks_presence_details_get_presence_type (
250       FOLKS_PRESENCE_DETAILS (individual));
251   presence = empathy_folks_presence_type_to_tp (folks_presence);
252
253   return empathy_icon_name_for_presence (presence);
254 }
255
256 const gchar *
257 empathy_protocol_name_for_contact (EmpathyContact *contact)
258 {
259   TpAccount *account;
260
261   g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
262
263   account = empathy_contact_get_account (contact);
264   if (account == NULL)
265     return NULL;
266
267   return tp_account_get_icon_name (account);
268 }
269
270 GdkPixbuf *
271 empathy_pixbuf_from_data (gchar *data,
272     gsize data_size)
273 {
274   return empathy_pixbuf_from_data_and_mime (data, data_size, NULL);
275 }
276
277 GdkPixbuf *
278 empathy_pixbuf_from_data_and_mime (gchar *data,
279            gsize data_size,
280            gchar **mime_type)
281 {
282   GdkPixbufLoader *loader;
283   GdkPixbufFormat *format;
284   GdkPixbuf *pixbuf = NULL;
285   gchar **mime_types;
286   GError *error = NULL;
287
288   if (!data)
289     return NULL;
290
291   loader = gdk_pixbuf_loader_new ();
292   if (!gdk_pixbuf_loader_write (loader, (guchar *) data, data_size, &error))
293     {
294       DEBUG ("Failed to write to pixbuf loader: %s",
295         error ? error->message : "No error given");
296       goto out;
297     }
298
299   if (!gdk_pixbuf_loader_close (loader, &error))
300     {
301       DEBUG ("Failed to close pixbuf loader: %s",
302         error ? error->message : "No error given");
303       goto out;
304     }
305
306   pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
307   if (pixbuf)
308     {
309       g_object_ref (pixbuf);
310
311       if (mime_type != NULL)
312         {
313           format = gdk_pixbuf_loader_get_format (loader);
314           mime_types = gdk_pixbuf_format_get_mime_types (format);
315
316           *mime_type = g_strdup (*mime_types);
317           if (mime_types[1] != NULL)
318             DEBUG ("Loader supports more than one mime "
319               "type! Picking the first one, %s",
320               *mime_type);
321
322           g_strfreev (mime_types);
323         }
324     }
325
326 out:
327   g_clear_error (&error);
328   g_object_unref (loader);
329
330   return pixbuf;
331 }
332
333 struct SizeData
334 {
335   gint width;
336   gint height;
337   gboolean preserve_aspect_ratio;
338 };
339
340 static void
341 pixbuf_from_avatar_size_prepared_cb (GdkPixbufLoader *loader,
342     int width,
343     int height,
344     struct SizeData *data)
345 {
346   g_return_if_fail (width > 0 && height > 0);
347
348   if (data->preserve_aspect_ratio && (data->width > 0 || data->height > 0))
349     {
350       if (width < data->width && height < data->height)
351         {
352           width = width;
353           height = height;
354         }
355
356       if (data->width < 0)
357         {
358           width = width * (double) data->height / (gdouble) height;
359           height = data->height;
360         }
361       else if (data->height < 0)
362         {
363           height = height * (double) data->width / (double) width;
364           width = data->width;
365         }
366       else if ((double) height * (double) data->width >
367            (double) width * (double) data->height)
368         {
369           width = 0.5 + (double) width * (double) data->height / (double) height;
370           height = data->height;
371         }
372       else
373         {
374           height = 0.5 + (double) height * (double) data->width / (double) width;
375           width = data->width;
376         }
377     }
378   else
379     {
380       if (data->width > 0)
381         width = data->width;
382
383       if (data->height > 0)
384         height = data->height;
385     }
386
387   gdk_pixbuf_loader_set_size (loader, width, height);
388 }
389
390 static void
391 empathy_avatar_pixbuf_roundify (GdkPixbuf *pixbuf)
392 {
393   gint width, height, rowstride;
394   guchar *pixels;
395
396   width = gdk_pixbuf_get_width (pixbuf);
397   height = gdk_pixbuf_get_height (pixbuf);
398   rowstride = gdk_pixbuf_get_rowstride (pixbuf);
399   pixels = gdk_pixbuf_get_pixels (pixbuf);
400
401   if (width < 6 || height < 6)
402     return;
403
404   /* Top left */
405   pixels[3] = 0;
406   pixels[7] = 0x80;
407   pixels[11] = 0xC0;
408   pixels[rowstride + 3] = 0x80;
409   pixels[rowstride * 2 + 3] = 0xC0;
410
411   /* Top right */
412   pixels[width * 4 - 1] = 0;
413   pixels[width * 4 - 5] = 0x80;
414   pixels[width * 4 - 9] = 0xC0;
415   pixels[rowstride + (width * 4) - 1] = 0x80;
416   pixels[(2 * rowstride) + (width * 4) - 1] = 0xC0;
417
418   /* Bottom left */
419   pixels[(height - 1) * rowstride + 3] = 0;
420   pixels[(height - 1) * rowstride + 7] = 0x80;
421   pixels[(height - 1) * rowstride + 11] = 0xC0;
422   pixels[(height - 2) * rowstride + 3] = 0x80;
423   pixels[(height - 3) * rowstride + 3] = 0xC0;
424
425   /* Bottom right */
426   pixels[height * rowstride - 1] = 0;
427   pixels[(height - 1) * rowstride - 1] = 0x80;
428   pixels[(height - 2) * rowstride - 1] = 0xC0;
429   pixels[height * rowstride - 5] = 0x80;
430   pixels[height * rowstride - 9] = 0xC0;
431 }
432
433 static gboolean
434 empathy_gdk_pixbuf_is_opaque (GdkPixbuf *pixbuf)
435 {
436   gint height, rowstride, i;
437   guchar *pixels;
438   guchar *row;
439
440   height = gdk_pixbuf_get_height (pixbuf);
441   rowstride = gdk_pixbuf_get_rowstride (pixbuf);
442   pixels = gdk_pixbuf_get_pixels (pixbuf);
443
444   row = pixels;
445   for (i = 3; i < rowstride; i+=4)
446     if (row[i] < 0xfe)
447       return FALSE;
448
449   for (i = 1; i < height - 1; i++)
450     {
451       row = pixels + (i*rowstride);
452       if (row[3] < 0xfe || row[rowstride-1] < 0xfe)
453         return FALSE;
454     }
455
456   row = pixels + ((height-1) * rowstride);
457   for (i = 3; i < rowstride; i+=4)
458     if (row[i] < 0xfe)
459       return FALSE;
460
461   return TRUE;
462 }
463
464 static GdkPixbuf *
465 pixbuf_round_corners (GdkPixbuf *pixbuf)
466 {
467   GdkPixbuf *result;
468
469   if (!gdk_pixbuf_get_has_alpha (pixbuf))
470     {
471       result = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8,
472           gdk_pixbuf_get_width (pixbuf),
473           gdk_pixbuf_get_height (pixbuf));
474
475       gdk_pixbuf_copy_area (pixbuf, 0, 0,
476           gdk_pixbuf_get_width (pixbuf),
477           gdk_pixbuf_get_height (pixbuf),
478           result,
479           0, 0);
480     }
481   else
482     {
483       result = g_object_ref (pixbuf);
484     }
485
486   if (empathy_gdk_pixbuf_is_opaque (result))
487     empathy_avatar_pixbuf_roundify (result);
488
489   return result;
490 }
491
492 static GdkPixbuf *
493 avatar_pixbuf_from_loader (GdkPixbufLoader *loader)
494 {
495   GdkPixbuf *pixbuf;
496
497   pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
498
499   return pixbuf_round_corners (pixbuf);
500 }
501
502 static GdkPixbuf *
503 empathy_pixbuf_from_avatar_scaled (EmpathyAvatar *avatar,
504     gint width,
505     gint height)
506 {
507   GdkPixbuf *pixbuf;
508   GdkPixbufLoader *loader;
509   struct SizeData data;
510   GError *error = NULL;
511
512   if (!avatar)
513     return NULL;
514
515   data.width = width;
516   data.height = height;
517   data.preserve_aspect_ratio = TRUE;
518
519   loader = gdk_pixbuf_loader_new ();
520
521   g_signal_connect (loader, "size-prepared",
522       G_CALLBACK (pixbuf_from_avatar_size_prepared_cb), &data);
523
524   if (avatar->len == 0)
525     {
526       g_warning ("Avatar has 0 length");
527       return NULL;
528     }
529   else if (!gdk_pixbuf_loader_write (loader, avatar->data, avatar->len, &error))
530     {
531       g_warning ("Couldn't write avatar image:%p with "
532           "length:%" G_GSIZE_FORMAT " to pixbuf loader: %s",
533           avatar->data, avatar->len, error->message);
534
535       g_error_free (error);
536       return NULL;
537     }
538
539   gdk_pixbuf_loader_close (loader, NULL);
540   pixbuf = avatar_pixbuf_from_loader (loader);
541
542   g_object_unref (loader);
543
544   return pixbuf;
545 }
546
547 GdkPixbuf *
548 empathy_pixbuf_avatar_from_contact_scaled (EmpathyContact *contact,
549     gint width,
550     gint height)
551 {
552   EmpathyAvatar *avatar;
553
554   g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
555
556   avatar = empathy_contact_get_avatar (contact);
557
558   return empathy_pixbuf_from_avatar_scaled (avatar, width, height);
559 }
560
561 typedef struct
562 {
563   GSimpleAsyncResult *result;
564   guint width;
565   guint height;
566   GCancellable *cancellable;
567 } PixbufAvatarFromIndividualClosure;
568
569 static PixbufAvatarFromIndividualClosure *
570 pixbuf_avatar_from_individual_closure_new (FolksIndividual *individual,
571     GSimpleAsyncResult *result,
572     gint width,
573     gint height,
574     GCancellable *cancellable)
575 {
576   PixbufAvatarFromIndividualClosure *closure;
577
578   g_return_val_if_fail (FOLKS_IS_INDIVIDUAL (individual), NULL);
579   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), NULL);
580
581   closure = g_slice_new0 (PixbufAvatarFromIndividualClosure);
582   closure->result = g_object_ref (result);
583   closure->width = width;
584   closure->height = height;
585
586   if (cancellable != NULL)
587     closure->cancellable = g_object_ref (cancellable);
588
589   return closure;
590 }
591
592 static void
593 pixbuf_avatar_from_individual_closure_free (
594     PixbufAvatarFromIndividualClosure *closure)
595 {
596   g_clear_object (&closure->cancellable);
597   g_object_unref (closure->result);
598   g_slice_free (PixbufAvatarFromIndividualClosure, closure);
599 }
600
601 /**
602  * @pixbuf: (transfer all)
603  *
604  * Return: (transfer all)
605  */
606 static GdkPixbuf *
607 transform_pixbuf (GdkPixbuf *pixbuf)
608 {
609   GdkPixbuf *result;
610
611   result = pixbuf_round_corners (pixbuf);
612   g_object_unref (pixbuf);
613
614   return result;
615 }
616
617 static void
618 avatar_icon_load_cb (GObject *object,
619     GAsyncResult *result,
620     gpointer user_data)
621 {
622   GLoadableIcon *icon = G_LOADABLE_ICON (object);
623   PixbufAvatarFromIndividualClosure *closure = user_data;
624   GInputStream *stream;
625   GError *error = NULL;
626   GdkPixbuf *pixbuf;
627   GdkPixbuf *final_pixbuf;
628
629   stream = g_loadable_icon_load_finish (icon, result, NULL, &error);
630   if (error != NULL)
631     {
632       DEBUG ("Failed to open avatar stream: %s", error->message);
633       g_simple_async_result_set_from_error (closure->result, error);
634       goto out;
635     }
636
637   pixbuf = gdk_pixbuf_new_from_stream_at_scale (stream,
638       closure->width, closure->height, TRUE, closure->cancellable, &error);
639
640   g_object_unref (stream);
641
642   if (pixbuf == NULL)
643     {
644       DEBUG ("Failed to read avatar: %s", error->message);
645       g_simple_async_result_set_from_error (closure->result, error);
646       goto out;
647     }
648
649   final_pixbuf = transform_pixbuf (pixbuf);
650
651   /* Pass ownership of final_pixbuf to the result */
652   g_simple_async_result_set_op_res_gpointer (closure->result,
653       final_pixbuf, g_object_unref);
654
655 out:
656   g_simple_async_result_complete (closure->result);
657
658   g_clear_error (&error);
659   pixbuf_avatar_from_individual_closure_free (closure);
660 }
661
662 void
663 empathy_pixbuf_avatar_from_individual_scaled_async (
664     FolksIndividual *individual,
665     gint width,
666     gint height,
667     GCancellable *cancellable,
668     GAsyncReadyCallback callback,
669     gpointer user_data)
670 {
671   GLoadableIcon *avatar_icon;
672   GSimpleAsyncResult *result;
673   PixbufAvatarFromIndividualClosure *closure;
674
675   result = g_simple_async_result_new (G_OBJECT (individual),
676       callback, user_data, empathy_pixbuf_avatar_from_individual_scaled_async);
677
678   avatar_icon = folks_avatar_details_get_avatar (
679       FOLKS_AVATAR_DETAILS (individual));
680
681   if (avatar_icon == NULL)
682     {
683       g_simple_async_result_set_error (result, G_IO_ERROR,
684         G_IO_ERROR_NOT_FOUND, "no avatar found");
685
686       g_simple_async_result_complete (result);
687       g_object_unref (result);
688       return;
689     }
690
691   closure = pixbuf_avatar_from_individual_closure_new (individual, result,
692       width, height, cancellable);
693
694   g_return_if_fail (closure != NULL);
695
696   g_loadable_icon_load_async (avatar_icon, width, cancellable,
697       avatar_icon_load_cb, closure);
698
699   g_object_unref (result);
700 }
701
702 /* Return a ref on the GdkPixbuf */
703 GdkPixbuf *
704 empathy_pixbuf_avatar_from_individual_scaled_finish (
705     FolksIndividual *individual,
706     GAsyncResult *result,
707     GError **error)
708 {
709   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
710   gboolean result_valid;
711   GdkPixbuf *pixbuf;
712
713   g_return_val_if_fail (FOLKS_IS_INDIVIDUAL (individual), NULL);
714   g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), NULL);
715
716   if (g_simple_async_result_propagate_error (simple, error))
717     return NULL;
718
719   result_valid = g_simple_async_result_is_valid (result,
720       G_OBJECT (individual),
721       empathy_pixbuf_avatar_from_individual_scaled_async);
722
723   g_return_val_if_fail (result_valid, NULL);
724
725   pixbuf = g_simple_async_result_get_op_res_gpointer (simple);
726   return pixbuf != NULL ? g_object_ref (pixbuf) : NULL;
727 }
728
729 GdkPixbuf *
730 empathy_pixbuf_contact_status_icon (EmpathyContact *contact,
731     gboolean show_protocol)
732 {
733   const gchar *icon_name;
734
735   g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
736
737   icon_name = empathy_icon_name_for_contact (contact);
738
739   if (icon_name == NULL)
740     return NULL;
741
742   return empathy_pixbuf_contact_status_icon_with_icon_name (contact,
743       icon_name, show_protocol);
744 }
745
746 static GdkPixbuf * empathy_pixbuf_protocol_from_contact_scaled (
747     EmpathyContact *contact,
748     gint width,
749     gint height);
750
751 GdkPixbuf *
752 empathy_pixbuf_contact_status_icon_with_icon_name (EmpathyContact *contact,
753     const gchar *icon_name,
754     gboolean show_protocol)
755 {
756   GdkPixbuf *pix_status;
757   GdkPixbuf *pix_protocol;
758   gchar *icon_filename;
759   gint height, width;
760   gint numerator, denominator;
761
762   g_return_val_if_fail (EMPATHY_IS_CONTACT (contact) ||
763       (show_protocol == FALSE), NULL);
764   g_return_val_if_fail (icon_name != NULL, NULL);
765
766   numerator = 3;
767   denominator = 4;
768
769   icon_filename = empathy_filename_from_icon_name (icon_name,
770       GTK_ICON_SIZE_MENU);
771
772   if (icon_filename == NULL)
773     {
774       DEBUG ("icon name: %s could not be found\n", icon_name);
775       return NULL;
776     }
777
778   pix_status = gdk_pixbuf_new_from_file (icon_filename, NULL);
779
780   if (pix_status == NULL)
781     {
782       DEBUG ("Could not open icon %s\n", icon_filename);
783       g_free (icon_filename);
784       return NULL;
785     }
786
787   g_free (icon_filename);
788
789   if (!show_protocol)
790     return pix_status;
791
792   height = gdk_pixbuf_get_height (pix_status);
793   width = gdk_pixbuf_get_width (pix_status);
794
795   pix_protocol = empathy_pixbuf_protocol_from_contact_scaled (contact,
796       width * numerator / denominator,
797       height * numerator / denominator);
798
799   if (pix_protocol == NULL)
800     return pix_status;
801
802   gdk_pixbuf_composite (pix_protocol, pix_status,
803       0, height - height * numerator / denominator,
804       width * numerator / denominator, height * numerator / denominator,
805       0, height - height * numerator / denominator,
806       1, 1,
807       GDK_INTERP_BILINEAR, 255);
808
809   g_object_unref (pix_protocol);
810
811   return pix_status;
812 }
813
814 static GdkPixbuf *
815 empathy_pixbuf_protocol_from_contact_scaled (EmpathyContact *contact,
816     gint width,
817     gint height)
818 {
819   TpAccount *account;
820   gchar *filename;
821   GdkPixbuf *pixbuf = NULL;
822
823   g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
824
825   account = empathy_contact_get_account (contact);
826   filename = empathy_filename_from_icon_name (
827       tp_account_get_icon_name (account), GTK_ICON_SIZE_MENU);
828
829   if (filename != NULL)
830     {
831       pixbuf = gdk_pixbuf_new_from_file_at_size (filename, width, height, NULL);
832       g_free (filename);
833     }
834
835   return pixbuf;
836 }
837
838 GdkPixbuf *
839 empathy_pixbuf_scale_down_if_necessary (GdkPixbuf *pixbuf,
840     gint max_size)
841 {
842   gint width, height;
843   gdouble factor;
844
845   width = gdk_pixbuf_get_width (pixbuf);
846   height = gdk_pixbuf_get_height (pixbuf);
847
848   if (width > 0 && (width > max_size || height > max_size))
849     {
850       factor = (gdouble) max_size / MAX (width, height);
851
852       width = width * factor;
853       height = height * factor;
854
855       return gdk_pixbuf_scale_simple (pixbuf, width, height, GDK_INTERP_HYPER);
856     }
857
858   return g_object_ref (pixbuf);
859 }
860
861 GdkPixbuf *
862 empathy_pixbuf_from_icon_name_sized (const gchar *icon_name,
863     gint size)
864 {
865   GtkIconTheme *theme;
866   GdkPixbuf *pixbuf;
867   GError *error = NULL;
868
869   if (!icon_name)
870     return NULL;
871
872   theme = gtk_icon_theme_get_default ();
873
874   pixbuf = gtk_icon_theme_load_icon (theme, icon_name, size, 0, &error);
875
876   if (error)
877     {
878       DEBUG ("Error loading icon: %s", error->message);
879       g_clear_error (&error);
880     }
881
882   return pixbuf;
883 }
884
885 GdkPixbuf *
886 empathy_pixbuf_from_icon_name (const gchar *icon_name,
887     GtkIconSize  icon_size)
888 {
889   gint w, h;
890   gint size = 48;
891
892   if (!icon_name)
893     return NULL;
894
895   if (gtk_icon_size_lookup (icon_size, &w, &h))
896     size = (w + h) / 2;
897
898   return empathy_pixbuf_from_icon_name_sized (icon_name, size);
899 }
900
901 gchar *
902 empathy_filename_from_icon_name (const gchar *icon_name,
903     GtkIconSize icon_size)
904 {
905   GtkIconTheme *icon_theme;
906   GtkIconInfo *icon_info;
907   gint w, h;
908   gint size = 48;
909   gchar *ret;
910
911   icon_theme = gtk_icon_theme_get_default ();
912
913   if (gtk_icon_size_lookup (icon_size, &w, &h))
914     size = (w + h) / 2;
915
916   icon_info = gtk_icon_theme_lookup_icon (icon_theme, icon_name, size, 0);
917   if (icon_info == NULL)
918     return NULL;
919
920   ret = g_strdup (gtk_icon_info_get_filename (icon_info));
921   gtk_icon_info_free (icon_info);
922
923   return ret;
924 }
925
926 /* Takes care of moving the window to the current workspace. */
927 void
928 empathy_window_present_with_time (GtkWindow *window,
929     guint32 timestamp)
930 {
931   GdkWindow *gdk_window;
932
933   g_return_if_fail (GTK_IS_WINDOW (window));
934
935   /* Move the window to the current workspace before trying to show it.
936    * This is the behaviour people expect when clicking on the statusbar icon. */
937   gdk_window = gtk_widget_get_window (GTK_WIDGET (window));
938
939   if (gdk_window)
940     {
941       gint x, y;
942       gint w, h;
943
944       /* Has no effect if the WM has viewports, like compiz */
945       gdk_x11_window_move_to_current_desktop (gdk_window);
946
947       /* If window is still off-screen, hide it to force it to
948        * reposition on the current workspace. */
949       gtk_window_get_position (window, &x, &y);
950       gtk_window_get_size (window, &w, &h);
951       if (!EMPATHY_RECT_IS_ON_SCREEN (x, y, w, h))
952         gtk_widget_hide (GTK_WIDGET (window));
953     }
954
955   if (timestamp == GDK_CURRENT_TIME)
956     gtk_window_present (window);
957   else
958     gtk_window_present_with_time (window, timestamp);
959 }
960
961 void
962 empathy_window_present (GtkWindow *window)
963 {
964   empathy_window_present_with_time (window, gtk_get_current_event_time ());
965 }
966
967 GtkWindow *
968 empathy_get_toplevel_window (GtkWidget *widget)
969 {
970   GtkWidget *toplevel;
971
972   g_return_val_if_fail (GTK_IS_WIDGET (widget), NULL);
973
974   toplevel = gtk_widget_get_toplevel (widget);
975   if (GTK_IS_WINDOW (toplevel) &&
976       gtk_widget_is_toplevel (toplevel))
977     return GTK_WINDOW (toplevel);
978
979   return NULL;
980 }
981
982 /** empathy_make_absolute_url_len:
983  * @url: an url
984  * @len: a length
985  *
986  * Same as #empathy_make_absolute_url but for a limited string length
987  */
988 gchar *
989 empathy_make_absolute_url_len (const gchar *url,
990     guint len)
991 {
992   g_return_val_if_fail (url != NULL, NULL);
993
994   if (g_str_has_prefix (url, "help:") ||
995       g_str_has_prefix (url, "mailto:") ||
996       strstr (url, ":/"))
997     return g_strndup (url, len);
998
999   if (strstr (url, "@"))
1000     return g_strdup_printf ("mailto:%.*s", len, url);
1001
1002   return g_strdup_printf ("http://%.*s", len, url);
1003 }
1004
1005 /** empathy_make_absolute_url:
1006  * @url: an url
1007  *
1008  * The URL opening code can't handle schemeless strings, so we try to be
1009  * smart and add http if there is no scheme or doesn't look like a mail
1010  * address. This should work in most cases, and let us click on strings
1011  * like "www.gnome.org".
1012  *
1013  * Returns: a newly allocated url with proper mailto: or http:// prefix, use
1014  * g_free when your are done with it
1015  */
1016 gchar *
1017 empathy_make_absolute_url (const gchar *url)
1018 {
1019   return empathy_make_absolute_url_len (url, strlen (url));
1020 }
1021
1022 void
1023 empathy_url_show (GtkWidget *parent,
1024       const char *url)
1025 {
1026   gchar  *real_url;
1027   GError *error = NULL;
1028
1029   g_return_if_fail (parent == NULL || GTK_IS_WIDGET (parent));
1030   g_return_if_fail (url != NULL);
1031
1032   real_url = empathy_make_absolute_url (url);
1033
1034   gtk_show_uri (parent ? gtk_widget_get_screen (parent) : NULL, real_url,
1035       gtk_get_current_event_time (), &error);
1036
1037   if (error)
1038     {
1039       GtkWidget *dialog;
1040
1041       dialog = gtk_message_dialog_new (NULL, 0,
1042           GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,
1043           _("Unable to open URI"));
1044
1045       gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
1046           "%s", error->message);
1047
1048       g_signal_connect (dialog, "response",
1049             G_CALLBACK (gtk_widget_destroy), NULL);
1050
1051       gtk_window_present (GTK_WINDOW (dialog));
1052
1053       g_clear_error (&error);
1054     }
1055
1056   g_free (real_url);
1057 }
1058
1059 void
1060 empathy_send_file (EmpathyContact *contact,
1061     GFile *file)
1062 {
1063   EmpathyFTFactory *factory;
1064   GtkRecentManager *manager;
1065   gchar *uri;
1066
1067   g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1068   g_return_if_fail (G_IS_FILE (file));
1069
1070   factory = empathy_ft_factory_dup_singleton ();
1071
1072   empathy_ft_factory_new_transfer_outgoing (factory, contact, file,
1073       empathy_get_current_action_time ());
1074
1075   uri = g_file_get_uri (file);
1076   manager = gtk_recent_manager_get_default ();
1077   gtk_recent_manager_add_item (manager, uri);
1078   g_free (uri);
1079
1080   g_object_unref (factory);
1081 }
1082
1083 void
1084 empathy_send_file_from_uri_list (EmpathyContact *contact,
1085     const gchar *uri_list)
1086 {
1087   const gchar *nl;
1088   GFile *file;
1089
1090   /* Only handle a single file for now. It would be wicked cool to be
1091      able to do multiple files, offering to zip them or whatever like
1092      nautilus-sendto does. Note that text/uri-list is defined to have
1093      each line terminated by \r\n, but we can be tolerant of applications
1094      that only use \n or don't terminate single-line entries.
1095   */
1096   nl = strstr (uri_list, "\r\n");
1097   if (!nl)
1098     nl = strchr (uri_list, '\n');
1099
1100   if (nl)
1101     {
1102       gchar *uri = g_strndup (uri_list, nl - uri_list);
1103       file = g_file_new_for_uri (uri);
1104       g_free (uri);
1105     }
1106   else
1107     {
1108       file = g_file_new_for_uri (uri_list);
1109     }
1110
1111   empathy_send_file (contact, file);
1112
1113   g_object_unref (file);
1114 }
1115
1116 static void
1117 file_manager_send_file_response_cb (GtkDialog *widget,
1118     gint response_id,
1119     EmpathyContact *contact)
1120 {
1121   GFile *file;
1122
1123   if (response_id == GTK_RESPONSE_OK)
1124     {
1125       file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (widget));
1126
1127       empathy_send_file (contact, file);
1128
1129       g_object_unref (file);
1130     }
1131
1132   g_object_unref (contact);
1133   gtk_widget_destroy (GTK_WIDGET (widget));
1134 }
1135
1136 static gboolean
1137 filter_cb (const GtkFileFilterInfo *filter_info,
1138     gpointer data)
1139 {
1140   /* filter out socket files */
1141   return tp_strdiff (filter_info->mime_type, "inode/socket");
1142 }
1143
1144 static GtkFileFilter *
1145 create_file_filter (void)
1146 {
1147   GtkFileFilter *filter;
1148
1149   filter = gtk_file_filter_new ();
1150
1151   gtk_file_filter_add_custom (filter, GTK_FILE_FILTER_MIME_TYPE, filter_cb,
1152     NULL, NULL);
1153
1154   return filter;
1155 }
1156
1157 void
1158 empathy_send_file_with_file_chooser (EmpathyContact *contact)
1159 {
1160   GtkWidget *widget;
1161   GtkWidget *button;
1162
1163   g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1164
1165   DEBUG ("Creating selection file chooser");
1166
1167   widget = gtk_file_chooser_dialog_new (_("Select a file"), NULL,
1168       GTK_FILE_CHOOSER_ACTION_OPEN,
1169       GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
1170       NULL);
1171
1172   /* send button */
1173   button = gtk_button_new_with_mnemonic (_("_Send"));
1174   gtk_button_set_image (GTK_BUTTON (button),
1175       gtk_image_new_from_icon_name (EMPATHY_IMAGE_DOCUMENT_SEND,
1176         GTK_ICON_SIZE_BUTTON));
1177   gtk_widget_show (button);
1178
1179   gtk_dialog_add_action_widget (GTK_DIALOG (widget), button,
1180       GTK_RESPONSE_OK);
1181
1182   gtk_widget_set_can_default (button, TRUE);
1183   gtk_dialog_set_default_response (GTK_DIALOG (widget),
1184       GTK_RESPONSE_OK);
1185
1186   gtk_file_chooser_set_local_only (GTK_FILE_CHOOSER (widget), FALSE);
1187
1188   gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (widget),
1189       g_get_home_dir ());
1190
1191   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (widget),
1192       create_file_filter ());
1193
1194   g_signal_connect (widget, "response",
1195       G_CALLBACK (file_manager_send_file_response_cb), g_object_ref (contact));
1196
1197   gtk_widget_show (widget);
1198 }
1199
1200 static void
1201 file_manager_receive_file_response_cb (GtkDialog *dialog,
1202     GtkResponseType response,
1203     EmpathyFTHandler *handler)
1204 {
1205   EmpathyFTFactory *factory;
1206   GFile *file;
1207
1208   if (response == GTK_RESPONSE_OK)
1209     {
1210       GFile *parent;
1211       GFileInfo *info;
1212       guint64 free_space, file_size;
1213       GError *error = NULL;
1214
1215       file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (dialog));
1216       parent = g_file_get_parent (file);
1217       info = g_file_query_filesystem_info (parent,
1218           G_FILE_ATTRIBUTE_FILESYSTEM_FREE, NULL, &error);
1219
1220       g_object_unref (parent);
1221
1222       if (error != NULL)
1223         {
1224           g_warning ("Error: %s", error->message);
1225
1226           g_object_unref (file);
1227           return;
1228         }
1229
1230       free_space = g_file_info_get_attribute_uint64 (info,
1231           G_FILE_ATTRIBUTE_FILESYSTEM_FREE);
1232       file_size = empathy_ft_handler_get_total_bytes (handler);
1233
1234       g_object_unref (info);
1235
1236       if (file_size > free_space)
1237         {
1238           GtkWidget *message = gtk_message_dialog_new (GTK_WINDOW (dialog),
1239             GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR,
1240             GTK_BUTTONS_CLOSE,
1241             _("Insufficient free space to save file"));
1242           char *file_size_str, *free_space_str;
1243
1244           file_size_str = g_format_size (file_size);
1245           free_space_str = g_format_size (free_space);
1246
1247           gtk_message_dialog_format_secondary_text (
1248               GTK_MESSAGE_DIALOG (message),
1249               _("%s of free space are required to save this "
1250                 "file, but only %s is available. Please "
1251                 "choose another location."),
1252             file_size_str, free_space_str);
1253
1254           gtk_dialog_run (GTK_DIALOG (message));
1255
1256           g_free (file_size_str);
1257           g_free (free_space_str);
1258           gtk_widget_destroy (message);
1259
1260           g_object_unref (file);
1261
1262           return;
1263         }
1264
1265       factory = empathy_ft_factory_dup_singleton ();
1266
1267       empathy_ft_factory_set_destination_for_incoming_handler (
1268           factory, handler, file);
1269
1270       g_object_unref (factory);
1271       g_object_unref (file);
1272     }
1273   else
1274     {
1275       /* unref the handler, as we dismissed the file chooser,
1276        * and refused the transfer.
1277        */
1278       g_object_unref (handler);
1279     }
1280
1281   gtk_widget_destroy (GTK_WIDGET (dialog));
1282 }
1283
1284 void
1285 empathy_receive_file_with_file_chooser (EmpathyFTHandler *handler)
1286 {
1287   GtkWidget *widget;
1288   const gchar *dir;
1289   EmpathyContact *contact;
1290   gchar *title;
1291
1292   contact = empathy_ft_handler_get_contact (handler);
1293   g_assert (contact != NULL);
1294
1295   title = g_strdup_printf (_("Incoming file from %s"),
1296     empathy_contact_get_alias (contact));
1297
1298   widget = gtk_file_chooser_dialog_new (title,
1299       NULL, GTK_FILE_CHOOSER_ACTION_SAVE,
1300       GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
1301       GTK_STOCK_SAVE, GTK_RESPONSE_OK,
1302       NULL);
1303
1304   gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (widget),
1305     empathy_ft_handler_get_filename (handler));
1306
1307   gtk_file_chooser_set_do_overwrite_confirmation
1308     (GTK_FILE_CHOOSER (widget), TRUE);
1309
1310   dir = g_get_user_special_dir (G_USER_DIRECTORY_DOWNLOAD);
1311   if (dir == NULL)
1312     /* Fallback to $HOME if $XDG_DOWNLOAD_DIR is not set */
1313     dir = g_get_home_dir ();
1314
1315   gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (widget), dir);
1316
1317   g_signal_connect (widget, "response",
1318       G_CALLBACK (file_manager_receive_file_response_cb), handler);
1319
1320   gtk_widget_show (widget);
1321   g_free (title);
1322 }
1323
1324 void
1325 empathy_make_color_whiter (GdkRGBA *color)
1326 {
1327   const GdkRGBA white = { 1.0, 1.0, 1.0, 1.0 };
1328
1329   color->red = (color->red + white.red) / 2;
1330   color->green = (color->green + white.green) / 2;
1331   color->blue = (color->blue + white.blue) / 2;
1332 }
1333
1334 static void
1335 menu_deactivate_cb (GtkMenu *menu,
1336   gpointer user_data)
1337 {
1338   /* FIXME: we shouldn't have to disconnect the signal (bgo #641327) */
1339   g_signal_handlers_disconnect_by_func (menu,
1340          menu_deactivate_cb, user_data);
1341
1342   gtk_menu_detach (menu);
1343 }
1344
1345 /* Convenient function to create a GtkMenu attached to @attach_to and detach
1346  * it when the menu is not displayed any more. This is useful when creating a
1347  * context menu that we want to get rid as soon as it as been displayed. */
1348 GtkWidget *
1349 empathy_context_menu_new (GtkWidget *attach_to)
1350 {
1351   GtkWidget *menu;
1352
1353   menu = gtk_menu_new ();
1354
1355   gtk_menu_attach_to_widget (GTK_MENU (menu), attach_to, NULL);
1356
1357   /* menu is initially unowned but gtk_menu_attach_to_widget () taked its
1358    * floating ref. We can either wait that @attach_to releases its ref when
1359    * it will be destroyed (when leaving Empathy most of the time) or explicitely
1360    * detach the menu when it's not displayed any more.
1361    * We go for the latter as we don't want to keep useless menus in memory
1362    * during the whole lifetime of Empathy. */
1363   g_signal_connect (menu, "deactivate", G_CALLBACK (menu_deactivate_cb), NULL);
1364
1365   return menu;
1366 }
1367
1368 gint64
1369 empathy_get_current_action_time (void)
1370 {
1371   return (tp_user_action_time_from_x11 (gtk_get_current_event_time ()));
1372 }
1373
1374 /* @words = empathy_live_search_strip_utf8_string (@text);
1375  *
1376  * User has to pass both so we don't have to compute @words ourself each time
1377  * this function is called. */
1378 gboolean
1379 empathy_individual_match_string (FolksIndividual *individual,
1380     const char *text,
1381     GPtrArray *words)
1382 {
1383   const gchar *str;
1384   GeeSet *personas;
1385   GeeIterator *iter;
1386   gboolean retval = FALSE;
1387
1388   /* check alias name */
1389   str = folks_alias_details_get_alias (FOLKS_ALIAS_DETAILS (individual));
1390
1391   if (empathy_live_search_match_words (str, words))
1392     return TRUE;
1393
1394   personas = folks_individual_get_personas (individual);
1395
1396   /* check contact id, remove the @server.com part */
1397   iter = gee_iterable_iterator (GEE_ITERABLE (personas));
1398   while (retval == FALSE && gee_iterator_next (iter))
1399     {
1400       FolksPersona *persona = gee_iterator_get (iter);
1401       const gchar *p;
1402
1403       if (empathy_folks_persona_is_interesting (persona))
1404         {
1405           str = folks_persona_get_display_id (persona);
1406
1407           /* Accept the persona if @text is a full prefix of his ID; that allows
1408            * user to find, say, a jabber contact by typing his JID. */
1409           if (g_str_has_prefix (str, text))
1410             {
1411               retval = TRUE;
1412             }
1413           else
1414             {
1415               gchar *dup_str = NULL;
1416               gboolean visible;
1417
1418               p = strstr (str, "@");
1419               if (p != NULL)
1420                 str = dup_str = g_strndup (str, p - str);
1421
1422               visible = empathy_live_search_match_words (str, words);
1423               g_free (dup_str);
1424               if (visible)
1425                 retval = TRUE;
1426             }
1427         }
1428       g_clear_object (&persona);
1429     }
1430   g_clear_object (&iter);
1431
1432   /* FIXME: Add more rules here, we could check phone numbers in
1433    * contact's vCard for example. */
1434   return retval;
1435 }
1436
1437 void
1438 empathy_launch_program (const gchar *dir,
1439     const gchar *name,
1440     const gchar *args)
1441 {
1442   GdkDisplay *display;
1443   GError *error = NULL;
1444   gchar *path, *cmd;
1445   GAppInfo *app_info;
1446   GdkAppLaunchContext *context = NULL;
1447
1448   /* Try to run from source directory if possible */
1449   path = g_build_filename (g_getenv ("EMPATHY_SRCDIR"), "src",
1450       name, NULL);
1451
1452   if (!g_file_test (path, G_FILE_TEST_EXISTS))
1453     {
1454       g_free (path);
1455       path = g_build_filename (dir, name, NULL);
1456     }
1457
1458   if (args != NULL)
1459     cmd = g_strconcat (path, " ", args, NULL);
1460   else
1461     cmd = g_strdup (path);
1462
1463   app_info = g_app_info_create_from_commandline (cmd, NULL, 0, &error);
1464   if (app_info == NULL)
1465     {
1466       DEBUG ("Failed to create app info: %s", error->message);
1467       g_error_free (error);
1468       goto out;
1469     }
1470
1471   display = gdk_display_get_default ();
1472   context = gdk_display_get_app_launch_context (display);
1473
1474   if (!g_app_info_launch (app_info, NULL, (GAppLaunchContext *) context,
1475       &error))
1476     {
1477       g_warning ("Failed to launch %s: %s", name, error->message);
1478       g_error_free (error);
1479       goto out;
1480     }
1481
1482 out:
1483   tp_clear_object (&app_info);
1484   tp_clear_object (&context);
1485   g_free (path);
1486   g_free (cmd);
1487 }
1488
1489 /* Most of the workspace manipulation code has been copied from libwnck
1490  * Copyright (C) 2001 Havoc Pennington
1491  * Copyright (C) 2005-2007 Vincent Untz
1492  */
1493 static void
1494 _wnck_activate_workspace (Screen *screen,
1495     int new_active_space,
1496     Time timestamp)
1497 {
1498   Display *display;
1499   Window root;
1500   XEvent xev;
1501
1502   display = DisplayOfScreen (screen);
1503   root = RootWindowOfScreen (screen);
1504
1505   xev.xclient.type = ClientMessage;
1506   xev.xclient.serial = 0;
1507   xev.xclient.send_event = True;
1508   xev.xclient.display = display;
1509   xev.xclient.window = root;
1510   xev.xclient.message_type = gdk_x11_get_xatom_by_name ("_NET_CURRENT_DESKTOP");
1511   xev.xclient.format = 32;
1512   xev.xclient.data.l[0] = new_active_space;
1513   xev.xclient.data.l[1] = timestamp;
1514   xev.xclient.data.l[2] = 0;
1515   xev.xclient.data.l[3] = 0;
1516   xev.xclient.data.l[4] = 0;
1517
1518   gdk_error_trap_push ();
1519   XSendEvent (display, root, False,
1520       SubstructureRedirectMask | SubstructureNotifyMask,
1521       &xev);
1522   XSync (display, False);
1523   gdk_error_trap_pop_ignored ();
1524 }
1525
1526 static gboolean
1527 _wnck_get_cardinal (Screen *screen,
1528     Window xwindow,
1529     Atom atom,
1530     int *val)
1531 {
1532   Display *display;
1533   Atom type;
1534   int format;
1535   gulong nitems;
1536   gulong bytes_after;
1537   gulong *num;
1538   int err, result;
1539
1540   display = DisplayOfScreen (screen);
1541
1542   *val = 0;
1543
1544   gdk_error_trap_push ();
1545   type = None;
1546   result = XGetWindowProperty (display, xwindow, atom,
1547       0, G_MAXLONG, False, XA_CARDINAL, &type, &format, &nitems,
1548       &bytes_after, (void *) &num);
1549   err = gdk_error_trap_pop ();
1550   if (err != Success ||
1551       result != Success)
1552     return FALSE;
1553
1554   if (type != XA_CARDINAL)
1555     {
1556       XFree (num);
1557       return FALSE;
1558     }
1559
1560   *val = *num;
1561
1562   XFree (num);
1563
1564   return TRUE;
1565 }
1566
1567 static int
1568 window_get_workspace (Screen *xscreen,
1569     Window win)
1570 {
1571   int number;
1572
1573   if (!_wnck_get_cardinal (xscreen, win,
1574         gdk_x11_get_xatom_by_name ("_NET_WM_DESKTOP"), &number))
1575     return -1;
1576
1577   return number;
1578 }
1579
1580 /* Ask X to move to the desktop on which @window currently is
1581  * and the present @window. */
1582 void
1583 empathy_move_to_window_desktop (GtkWindow *window,
1584     guint32 timestamp)
1585 {
1586   GdkScreen *screen;
1587   Screen *xscreen;
1588   GdkWindow *gdk_window;
1589   int workspace;
1590
1591   screen = gtk_window_get_screen (window);
1592   xscreen = gdk_x11_screen_get_xscreen (screen);
1593   gdk_window = gtk_widget_get_window (GTK_WIDGET (window));
1594
1595   workspace = window_get_workspace (xscreen,
1596       gdk_x11_window_get_xid (gdk_window));
1597   if (workspace == -1)
1598     goto out;
1599
1600   _wnck_activate_workspace (xscreen, workspace, timestamp);
1601
1602 out:
1603   gtk_window_present_with_time (window, timestamp);
1604 }
1605
1606 void
1607 empathy_set_css_provider (GtkWidget *widget)
1608 {
1609   GtkCssProvider *provider;
1610   gchar *filename;
1611   GError *error = NULL;
1612   GdkScreen *screen;
1613
1614   filename = empathy_file_lookup ("empathy.css", "data");
1615
1616   provider = gtk_css_provider_new ();
1617
1618   if (!gtk_css_provider_load_from_path (provider, filename, &error))
1619     {
1620       g_warning ("Failed to load css file '%s': %s", filename, error->message);
1621       g_error_free (error);
1622       goto out;
1623     }
1624
1625   if (widget != NULL)
1626     screen = gtk_widget_get_screen (widget);
1627   else
1628     screen = gdk_screen_get_default ();
1629
1630   gtk_style_context_add_provider_for_screen (screen,
1631       GTK_STYLE_PROVIDER (provider),
1632       GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
1633
1634 out:
1635   g_free (filename);
1636   g_object_unref (provider);
1637 }
1638
1639 static gboolean
1640 launch_app_info (GAppInfo *app_info,
1641     GError **error)
1642 {
1643   GdkAppLaunchContext *context = NULL;
1644   GdkDisplay *display;
1645   GError *err = NULL;
1646
1647   display = gdk_display_get_default ();
1648   context = gdk_display_get_app_launch_context (display);
1649
1650   if (!g_app_info_launch (app_info, NULL, (GAppLaunchContext *) context,
1651         &err))
1652     {
1653       DEBUG ("Failed to launch %s: %s",
1654           g_app_info_get_display_name (app_info), err->message);
1655       g_propagate_error (error, err);
1656       return FALSE;
1657     }
1658
1659   tp_clear_object (&context);
1660   return TRUE;
1661 }
1662
1663 gboolean
1664 empathy_launch_external_app (const gchar *desktop_file,
1665     const gchar *args,
1666     GError **error)
1667 {
1668   GDesktopAppInfo *desktop_info;
1669   gboolean result;
1670   GError *err = NULL;
1671
1672   desktop_info = g_desktop_app_info_new (desktop_file);
1673   if (desktop_info == NULL)
1674     {
1675       DEBUG ("%s not found", desktop_file);
1676
1677       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1678           "%s not found", desktop_file);
1679       return FALSE;
1680     }
1681
1682   if (args == NULL)
1683     {
1684       result = launch_app_info (G_APP_INFO (desktop_info), error);
1685     }
1686   else
1687     {
1688       gchar *cmd;
1689       GAppInfo *app_info;
1690
1691       /* glib doesn't have API to start a desktop file with args... (#637875) */
1692       cmd = g_strdup_printf ("%s %s", g_app_info_get_commandline (
1693             (GAppInfo *) desktop_info), args);
1694
1695       app_info = g_app_info_create_from_commandline (cmd, NULL, 0, &err);
1696       if (app_info == NULL)
1697         {
1698           DEBUG ("Failed to launch '%s': %s", cmd, err->message);
1699           g_free (cmd);
1700           g_object_unref (desktop_info);
1701           g_propagate_error (error, err);
1702           return FALSE;
1703         }
1704
1705       result = launch_app_info (app_info, error);
1706
1707       g_object_unref (app_info);
1708       g_free (cmd);
1709     }
1710
1711   g_object_unref (desktop_info);
1712   return result;
1713 }