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