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