]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-ui-utils.c
ui-utils: remove unused public functions
[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 avatar_pixbuf_from_loader (GdkPixbufLoader *loader)
472 {
473   GdkPixbuf *pixbuf;
474
475   pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
476
477   if (!gdk_pixbuf_get_has_alpha (pixbuf))
478     {
479       GdkPixbuf *rounded_pixbuf;
480
481       rounded_pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8,
482           gdk_pixbuf_get_width (pixbuf),
483           gdk_pixbuf_get_height (pixbuf));
484
485       gdk_pixbuf_copy_area (pixbuf, 0, 0,
486           gdk_pixbuf_get_width (pixbuf),
487           gdk_pixbuf_get_height (pixbuf),
488           rounded_pixbuf,
489           0, 0);
490
491       pixbuf = rounded_pixbuf;
492     }
493   else
494     {
495       g_object_ref (pixbuf);
496     }
497
498   if (empathy_gdk_pixbuf_is_opaque (pixbuf))
499     empathy_avatar_pixbuf_roundify (pixbuf);
500
501   return pixbuf;
502 }
503
504 static GdkPixbuf *
505 empathy_pixbuf_from_avatar_scaled (EmpathyAvatar *avatar,
506     gint width,
507     gint height)
508 {
509   GdkPixbuf *pixbuf;
510   GdkPixbufLoader *loader;
511   struct SizeData data;
512   GError *error = NULL;
513
514   if (!avatar)
515     return NULL;
516
517   data.width = width;
518   data.height = height;
519   data.preserve_aspect_ratio = TRUE;
520
521   loader = gdk_pixbuf_loader_new ();
522
523   g_signal_connect (loader, "size-prepared",
524       G_CALLBACK (pixbuf_from_avatar_size_prepared_cb), &data);
525
526   if (avatar->len == 0)
527     {
528       g_warning ("Avatar has 0 length");
529       return NULL;
530     }
531   else if (!gdk_pixbuf_loader_write (loader, avatar->data, avatar->len, &error))
532     {
533       g_warning ("Couldn't write avatar image:%p with "
534           "length:%" G_GSIZE_FORMAT " to pixbuf loader: %s",
535           avatar->data, avatar->len, error->message);
536
537       g_error_free (error);
538       return NULL;
539     }
540
541   gdk_pixbuf_loader_close (loader, NULL);
542   pixbuf = avatar_pixbuf_from_loader (loader);
543
544   g_object_unref (loader);
545
546   return pixbuf;
547 }
548
549 GdkPixbuf *
550 empathy_pixbuf_avatar_from_contact_scaled (EmpathyContact *contact,
551     gint width,
552     gint height)
553 {
554   EmpathyAvatar *avatar;
555
556   g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
557
558   avatar = empathy_contact_get_avatar (contact);
559
560   return empathy_pixbuf_from_avatar_scaled (avatar, width, height);
561 }
562
563 typedef struct
564 {
565   FolksIndividual *individual;
566   GSimpleAsyncResult *result;
567   guint width;
568   guint height;
569   struct SizeData size_data;
570   GdkPixbufLoader *loader;
571   GCancellable *cancellable;
572   guint8 data[512];
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->individual = g_object_ref (individual);
589   closure->result = g_object_ref (result);
590   closure->width = width;
591   closure->height = height;
592
593   if (cancellable != NULL)
594     closure->cancellable = g_object_ref (cancellable);
595
596   return closure;
597 }
598
599 static void
600 pixbuf_avatar_from_individual_closure_free (
601     PixbufAvatarFromIndividualClosure *closure)
602 {
603   g_clear_object (&closure->cancellable);
604   tp_clear_object (&closure->loader);
605   g_object_unref (closure->individual);
606   g_object_unref (closure->result);
607   g_free (closure);
608 }
609
610 static void
611 avatar_icon_load_close_cb (GObject *object,
612     GAsyncResult *result,
613     gpointer user_data)
614 {
615   GError *error = NULL;
616
617   g_input_stream_close_finish (G_INPUT_STREAM (object), result, &error);
618
619   if (error != NULL)
620     {
621       DEBUG ("Failed to close pixbuf stream: %s", error->message);
622       g_error_free (error);
623     }
624 }
625
626 static void
627 avatar_icon_load_read_cb (GObject *object,
628     GAsyncResult *result,
629     gpointer user_data)
630 {
631   GInputStream *stream = G_INPUT_STREAM (object);
632   PixbufAvatarFromIndividualClosure *closure = user_data;
633   gssize n_read;
634   GError *error = NULL;
635
636   /* Finish reading this chunk from the stream */
637   n_read = g_input_stream_read_finish (stream, result, &error);
638   if (error != NULL)
639     {
640       DEBUG ("Failed to finish read from pixbuf stream: %s",
641         error->message);
642
643       g_simple_async_result_set_from_error (closure->result, error);
644       goto out_close;
645     }
646
647   /* Write the chunk to the pixbuf loader */
648   if (!gdk_pixbuf_loader_write (closure->loader, (guchar *) closure->data,
649       n_read, &error))
650     {
651       DEBUG ("Failed to write to pixbuf loader: %s",
652         error ? error->message : "No error given");
653
654       g_simple_async_result_set_from_error (closure->result, error);
655       goto out_close;
656     }
657
658   if (n_read == 0)
659     {
660       /* EOF? */
661       if (!gdk_pixbuf_loader_close (closure->loader, &error))
662         {
663           DEBUG ("Failed to close pixbuf loader: %s",
664               error ? error->message : "No error given");
665
666           g_simple_async_result_set_from_error (closure->result, error);
667           goto out;
668         }
669
670       /* We're done. */
671       g_simple_async_result_set_op_res_gpointer (closure->result,
672           avatar_pixbuf_from_loader (closure->loader),
673           g_object_unref);
674
675       goto out;
676     }
677   else
678     {
679       /* Loop round and read another chunk. */
680       g_input_stream_read_async (stream, closure->data,
681         G_N_ELEMENTS (closure->data),
682         G_PRIORITY_DEFAULT, closure->cancellable,
683         avatar_icon_load_read_cb, closure);
684
685       return;
686   }
687
688 out_close:
689   /* We must close the pixbuf loader before unreffing it. */
690   gdk_pixbuf_loader_close (closure->loader, NULL);
691
692 out:
693   /* Close the file for safety (even though it should be
694    * automatically closed when the stream is finalised). */
695   g_input_stream_close_async (stream, G_PRIORITY_DEFAULT, NULL,
696       (GAsyncReadyCallback) avatar_icon_load_close_cb, NULL);
697
698   g_simple_async_result_complete (closure->result);
699
700   g_clear_error (&error);
701   pixbuf_avatar_from_individual_closure_free (closure);
702 }
703
704 static void
705 avatar_icon_load_cb (GObject *object,
706     GAsyncResult *result,
707     gpointer user_data)
708 {
709   GLoadableIcon *icon = G_LOADABLE_ICON (object);
710   PixbufAvatarFromIndividualClosure *closure = user_data;
711   GInputStream *stream;
712   GError *error = NULL;
713
714   stream = g_loadable_icon_load_finish (icon, result, NULL, &error);
715   if (error != NULL)
716     {
717       DEBUG ("Failed to open avatar stream: %s", error->message);
718       g_simple_async_result_set_from_error (closure->result, error);
719       goto out;
720     }
721
722   closure->size_data.width = closure->width;
723   closure->size_data.height = closure->height;
724   closure->size_data.preserve_aspect_ratio = TRUE;
725
726   /* Load the data into a pixbuf loader in chunks. */
727   closure->loader = gdk_pixbuf_loader_new ();
728
729   g_signal_connect (closure->loader, "size-prepared",
730       G_CALLBACK (pixbuf_from_avatar_size_prepared_cb),
731       &(closure->size_data));
732
733   /* Begin to read the first chunk. */
734   g_input_stream_read_async (stream, closure->data,
735       G_N_ELEMENTS (closure->data),
736       G_PRIORITY_DEFAULT, closure->cancellable,
737       avatar_icon_load_read_cb, closure);
738
739   g_object_unref (stream);
740
741   return;
742
743 out:
744   g_simple_async_result_complete (closure->result);
745
746   g_clear_error (&error);
747   tp_clear_object (&stream);
748   pixbuf_avatar_from_individual_closure_free (closure);
749 }
750
751 void
752 empathy_pixbuf_avatar_from_individual_scaled_async (
753     FolksIndividual *individual,
754     gint width,
755     gint height,
756     GCancellable *cancellable,
757     GAsyncReadyCallback callback,
758     gpointer user_data)
759 {
760   GLoadableIcon *avatar_icon;
761   GSimpleAsyncResult *result;
762   PixbufAvatarFromIndividualClosure *closure;
763
764   result = g_simple_async_result_new (G_OBJECT (individual),
765       callback, user_data, empathy_pixbuf_avatar_from_individual_scaled_async);
766
767   avatar_icon = folks_avatar_details_get_avatar (
768       FOLKS_AVATAR_DETAILS (individual));
769
770   if (avatar_icon == NULL)
771     {
772       g_simple_async_result_set_error (result, G_IO_ERROR,
773         G_IO_ERROR_NOT_FOUND, "no avatar found");
774
775       g_simple_async_result_complete (result);
776       g_object_unref (result);
777       return;
778     }
779
780   closure = pixbuf_avatar_from_individual_closure_new (individual, result,
781       width, height, cancellable);
782
783   g_return_if_fail (closure != NULL);
784
785   g_loadable_icon_load_async (avatar_icon, width, cancellable,
786       avatar_icon_load_cb, closure);
787
788   g_object_unref (result);
789 }
790
791 /* Return a ref on the GdkPixbuf */
792 GdkPixbuf *
793 empathy_pixbuf_avatar_from_individual_scaled_finish (
794     FolksIndividual *individual,
795     GAsyncResult *result,
796     GError **error)
797 {
798   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
799   gboolean result_valid;
800   GdkPixbuf *pixbuf;
801
802   g_return_val_if_fail (FOLKS_IS_INDIVIDUAL (individual), NULL);
803   g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), NULL);
804
805   if (g_simple_async_result_propagate_error (simple, error))
806     return NULL;
807
808   result_valid = g_simple_async_result_is_valid (result,
809       G_OBJECT (individual),
810       empathy_pixbuf_avatar_from_individual_scaled_async);
811
812   g_return_val_if_fail (result_valid, NULL);
813
814   pixbuf = g_simple_async_result_get_op_res_gpointer (simple);
815   return pixbuf != NULL ? g_object_ref (pixbuf) : NULL;
816 }
817
818 GdkPixbuf *
819 empathy_pixbuf_contact_status_icon (EmpathyContact *contact,
820     gboolean show_protocol)
821 {
822   const gchar *icon_name;
823
824   g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
825
826   icon_name = empathy_icon_name_for_contact (contact);
827
828   if (icon_name == NULL)
829     return NULL;
830
831   return empathy_pixbuf_contact_status_icon_with_icon_name (contact,
832       icon_name, show_protocol);
833 }
834
835 static GdkPixbuf * empathy_pixbuf_protocol_from_contact_scaled (
836     EmpathyContact *contact,
837     gint width,
838     gint height);
839
840 GdkPixbuf *
841 empathy_pixbuf_contact_status_icon_with_icon_name (EmpathyContact *contact,
842     const gchar *icon_name,
843     gboolean show_protocol)
844 {
845   GdkPixbuf *pix_status;
846   GdkPixbuf *pix_protocol;
847   gchar *icon_filename;
848   gint height, width;
849   gint numerator, denominator;
850
851   g_return_val_if_fail (EMPATHY_IS_CONTACT (contact) ||
852       (show_protocol == FALSE), NULL);
853   g_return_val_if_fail (icon_name != NULL, NULL);
854
855   numerator = 3;
856   denominator = 4;
857
858   icon_filename = empathy_filename_from_icon_name (icon_name,
859       GTK_ICON_SIZE_MENU);
860
861   if (icon_filename == NULL)
862     {
863       DEBUG ("icon name: %s could not be found\n", icon_name);
864       return NULL;
865     }
866
867   pix_status = gdk_pixbuf_new_from_file (icon_filename, NULL);
868
869   if (pix_status == NULL)
870     {
871       DEBUG ("Could not open icon %s\n", icon_filename);
872       g_free (icon_filename);
873       return NULL;
874     }
875
876   g_free (icon_filename);
877
878   if (!show_protocol)
879     return pix_status;
880
881   height = gdk_pixbuf_get_height (pix_status);
882   width = gdk_pixbuf_get_width (pix_status);
883
884   pix_protocol = empathy_pixbuf_protocol_from_contact_scaled (contact,
885       width * numerator / denominator,
886       height * numerator / denominator);
887
888   if (pix_protocol == NULL)
889     return pix_status;
890
891   gdk_pixbuf_composite (pix_protocol, pix_status,
892       0, height - height * numerator / denominator,
893       width * numerator / denominator, height * numerator / denominator,
894       0, height - height * numerator / denominator,
895       1, 1,
896       GDK_INTERP_BILINEAR, 255);
897
898   g_object_unref (pix_protocol);
899
900   return pix_status;
901 }
902
903 static GdkPixbuf *
904 empathy_pixbuf_protocol_from_contact_scaled (EmpathyContact *contact,
905     gint width,
906     gint height)
907 {
908   TpAccount *account;
909   gchar *filename;
910   GdkPixbuf *pixbuf = NULL;
911
912   g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
913
914   account = empathy_contact_get_account (contact);
915   filename = empathy_filename_from_icon_name (
916       tp_account_get_icon_name (account), GTK_ICON_SIZE_MENU);
917
918   if (filename != NULL)
919     {
920       pixbuf = gdk_pixbuf_new_from_file_at_size (filename, width, height, NULL);
921       g_free (filename);
922     }
923
924   return pixbuf;
925 }
926
927 GdkPixbuf *
928 empathy_pixbuf_scale_down_if_necessary (GdkPixbuf *pixbuf,
929     gint max_size)
930 {
931   gint width, height;
932   gdouble factor;
933
934   width = gdk_pixbuf_get_width (pixbuf);
935   height = gdk_pixbuf_get_height (pixbuf);
936
937   if (width > 0 && (width > max_size || height > max_size))
938     {
939       factor = (gdouble) max_size / MAX (width, height);
940
941       width = width * factor;
942       height = height * factor;
943
944       return gdk_pixbuf_scale_simple (pixbuf, width, height, GDK_INTERP_HYPER);
945     }
946
947   return g_object_ref (pixbuf);
948 }
949
950 GdkPixbuf *
951 empathy_pixbuf_from_icon_name_sized (const gchar *icon_name,
952     gint size)
953 {
954   GtkIconTheme *theme;
955   GdkPixbuf *pixbuf;
956   GError *error = NULL;
957
958   if (!icon_name)
959     return NULL;
960
961   theme = gtk_icon_theme_get_default ();
962
963   pixbuf = gtk_icon_theme_load_icon (theme, icon_name, size, 0, &error);
964
965   if (error)
966     {
967       DEBUG ("Error loading icon: %s", error->message);
968       g_clear_error (&error);
969     }
970
971   return pixbuf;
972 }
973
974 GdkPixbuf *
975 empathy_pixbuf_from_icon_name (const gchar *icon_name,
976     GtkIconSize  icon_size)
977 {
978   gint w, h;
979   gint size = 48;
980
981   if (!icon_name)
982     return NULL;
983
984   if (gtk_icon_size_lookup (icon_size, &w, &h))
985     size = (w + h) / 2;
986
987   return empathy_pixbuf_from_icon_name_sized (icon_name, size);
988 }
989
990 gchar *
991 empathy_filename_from_icon_name (const gchar *icon_name,
992     GtkIconSize icon_size)
993 {
994   GtkIconTheme *icon_theme;
995   GtkIconInfo *icon_info;
996   gint w, h;
997   gint size = 48;
998   gchar *ret;
999
1000   icon_theme = gtk_icon_theme_get_default ();
1001
1002   if (gtk_icon_size_lookup (icon_size, &w, &h))
1003     size = (w + h) / 2;
1004
1005   icon_info = gtk_icon_theme_lookup_icon (icon_theme, icon_name, size, 0);
1006   if (icon_info == NULL)
1007     return NULL;
1008
1009   ret = g_strdup (gtk_icon_info_get_filename (icon_info));
1010   gtk_icon_info_free (icon_info);
1011
1012   return ret;
1013 }
1014
1015 /* Takes care of moving the window to the current workspace. */
1016 void
1017 empathy_window_present_with_time (GtkWindow *window,
1018     guint32 timestamp)
1019 {
1020   GdkWindow *gdk_window;
1021
1022   g_return_if_fail (GTK_IS_WINDOW (window));
1023
1024   /* Move the window to the current workspace before trying to show it.
1025    * This is the behaviour people expect when clicking on the statusbar icon. */
1026   gdk_window = gtk_widget_get_window (GTK_WIDGET (window));
1027
1028   if (gdk_window)
1029     {
1030       gint x, y;
1031       gint w, h;
1032
1033       /* Has no effect if the WM has viewports, like compiz */
1034       gdk_x11_window_move_to_current_desktop (gdk_window);
1035
1036       /* If window is still off-screen, hide it to force it to
1037        * reposition on the current workspace. */
1038       gtk_window_get_position (window, &x, &y);
1039       gtk_window_get_size (window, &w, &h);
1040       if (!EMPATHY_RECT_IS_ON_SCREEN (x, y, w, h))
1041         gtk_widget_hide (GTK_WIDGET (window));
1042     }
1043
1044   if (timestamp == GDK_CURRENT_TIME)
1045     gtk_window_present (window);
1046   else
1047     gtk_window_present_with_time (window, timestamp);
1048 }
1049
1050 void
1051 empathy_window_present (GtkWindow *window)
1052 {
1053   empathy_window_present_with_time (window, gtk_get_current_event_time ());
1054 }
1055
1056 GtkWindow *
1057 empathy_get_toplevel_window (GtkWidget *widget)
1058 {
1059   GtkWidget *toplevel;
1060
1061   g_return_val_if_fail (GTK_IS_WIDGET (widget), NULL);
1062
1063   toplevel = gtk_widget_get_toplevel (widget);
1064   if (GTK_IS_WINDOW (toplevel) &&
1065       gtk_widget_is_toplevel (toplevel))
1066     return GTK_WINDOW (toplevel);
1067
1068   return NULL;
1069 }
1070
1071 /** empathy_make_absolute_url_len:
1072  * @url: an url
1073  * @len: a length
1074  *
1075  * Same as #empathy_make_absolute_url but for a limited string length
1076  */
1077 gchar *
1078 empathy_make_absolute_url_len (const gchar *url,
1079     guint len)
1080 {
1081   g_return_val_if_fail (url != NULL, NULL);
1082
1083   if (g_str_has_prefix (url, "help:") ||
1084       g_str_has_prefix (url, "mailto:") ||
1085       strstr (url, ":/"))
1086     return g_strndup (url, len);
1087
1088   if (strstr (url, "@"))
1089     return g_strdup_printf ("mailto:%.*s", len, url);
1090
1091   return g_strdup_printf ("http://%.*s", len, url);
1092 }
1093
1094 /** empathy_make_absolute_url:
1095  * @url: an url
1096  *
1097  * The URL opening code can't handle schemeless strings, so we try to be
1098  * smart and add http if there is no scheme or doesn't look like a mail
1099  * address. This should work in most cases, and let us click on strings
1100  * like "www.gnome.org".
1101  *
1102  * Returns: a newly allocated url with proper mailto: or http:// prefix, use
1103  * g_free when your are done with it
1104  */
1105 gchar *
1106 empathy_make_absolute_url (const gchar *url)
1107 {
1108   return empathy_make_absolute_url_len (url, strlen (url));
1109 }
1110
1111 void
1112 empathy_url_show (GtkWidget *parent,
1113       const char *url)
1114 {
1115   gchar  *real_url;
1116   GError *error = NULL;
1117
1118   g_return_if_fail (parent == NULL || GTK_IS_WIDGET (parent));
1119   g_return_if_fail (url != NULL);
1120
1121   real_url = empathy_make_absolute_url (url);
1122
1123   gtk_show_uri (parent ? gtk_widget_get_screen (parent) : NULL, real_url,
1124       gtk_get_current_event_time (), &error);
1125
1126   if (error)
1127     {
1128       GtkWidget *dialog;
1129
1130       dialog = gtk_message_dialog_new (NULL, 0,
1131           GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,
1132           _("Unable to open URI"));
1133
1134       gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
1135           "%s", error->message);
1136
1137       g_signal_connect (dialog, "response",
1138             G_CALLBACK (gtk_widget_destroy), NULL);
1139
1140       gtk_window_present (GTK_WINDOW (dialog));
1141
1142       g_clear_error (&error);
1143     }
1144
1145   g_free (real_url);
1146 }
1147
1148 void
1149 empathy_send_file (EmpathyContact *contact,
1150     GFile *file)
1151 {
1152   EmpathyFTFactory *factory;
1153   GtkRecentManager *manager;
1154   gchar *uri;
1155
1156   g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1157   g_return_if_fail (G_IS_FILE (file));
1158
1159   factory = empathy_ft_factory_dup_singleton ();
1160
1161   empathy_ft_factory_new_transfer_outgoing (factory, contact, file,
1162       empathy_get_current_action_time ());
1163
1164   uri = g_file_get_uri (file);
1165   manager = gtk_recent_manager_get_default ();
1166   gtk_recent_manager_add_item (manager, uri);
1167   g_free (uri);
1168
1169   g_object_unref (factory);
1170 }
1171
1172 void
1173 empathy_send_file_from_uri_list (EmpathyContact *contact,
1174     const gchar *uri_list)
1175 {
1176   const gchar *nl;
1177   GFile *file;
1178
1179   /* Only handle a single file for now. It would be wicked cool to be
1180      able to do multiple files, offering to zip them or whatever like
1181      nautilus-sendto does. Note that text/uri-list is defined to have
1182      each line terminated by \r\n, but we can be tolerant of applications
1183      that only use \n or don't terminate single-line entries.
1184   */
1185   nl = strstr (uri_list, "\r\n");
1186   if (!nl)
1187     nl = strchr (uri_list, '\n');
1188
1189   if (nl)
1190     {
1191       gchar *uri = g_strndup (uri_list, nl - uri_list);
1192       file = g_file_new_for_uri (uri);
1193       g_free (uri);
1194     }
1195   else
1196     {
1197       file = g_file_new_for_uri (uri_list);
1198     }
1199
1200   empathy_send_file (contact, file);
1201
1202   g_object_unref (file);
1203 }
1204
1205 static void
1206 file_manager_send_file_response_cb (GtkDialog *widget,
1207     gint response_id,
1208     EmpathyContact *contact)
1209 {
1210   GFile *file;
1211
1212   if (response_id == GTK_RESPONSE_OK)
1213     {
1214       file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (widget));
1215
1216       empathy_send_file (contact, file);
1217
1218       g_object_unref (file);
1219     }
1220
1221   g_object_unref (contact);
1222   gtk_widget_destroy (GTK_WIDGET (widget));
1223 }
1224
1225 static gboolean
1226 filter_cb (const GtkFileFilterInfo *filter_info,
1227     gpointer data)
1228 {
1229   /* filter out socket files */
1230   return tp_strdiff (filter_info->mime_type, "inode/socket");
1231 }
1232
1233 static GtkFileFilter *
1234 create_file_filter (void)
1235 {
1236   GtkFileFilter *filter;
1237
1238   filter = gtk_file_filter_new ();
1239
1240   gtk_file_filter_add_custom (filter, GTK_FILE_FILTER_MIME_TYPE, filter_cb,
1241     NULL, NULL);
1242
1243   return filter;
1244 }
1245
1246 void
1247 empathy_send_file_with_file_chooser (EmpathyContact *contact)
1248 {
1249   GtkWidget *widget;
1250   GtkWidget *button;
1251
1252   g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1253
1254   DEBUG ("Creating selection file chooser");
1255
1256   widget = gtk_file_chooser_dialog_new (_("Select a file"), NULL,
1257       GTK_FILE_CHOOSER_ACTION_OPEN,
1258       GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
1259       NULL);
1260
1261   /* send button */
1262   button = gtk_button_new_with_mnemonic (_("_Send"));
1263   gtk_button_set_image (GTK_BUTTON (button),
1264       gtk_image_new_from_icon_name (EMPATHY_IMAGE_DOCUMENT_SEND,
1265         GTK_ICON_SIZE_BUTTON));
1266   gtk_widget_show (button);
1267
1268   gtk_dialog_add_action_widget (GTK_DIALOG (widget), button,
1269       GTK_RESPONSE_OK);
1270
1271   gtk_widget_set_can_default (button, TRUE);
1272   gtk_dialog_set_default_response (GTK_DIALOG (widget),
1273       GTK_RESPONSE_OK);
1274
1275   gtk_file_chooser_set_local_only (GTK_FILE_CHOOSER (widget), FALSE);
1276
1277   gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (widget),
1278       g_get_home_dir ());
1279
1280   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (widget),
1281       create_file_filter ());
1282
1283   g_signal_connect (widget, "response",
1284       G_CALLBACK (file_manager_send_file_response_cb), g_object_ref (contact));
1285
1286   gtk_widget_show (widget);
1287 }
1288
1289 static void
1290 file_manager_receive_file_response_cb (GtkDialog *dialog,
1291     GtkResponseType response,
1292     EmpathyFTHandler *handler)
1293 {
1294   EmpathyFTFactory *factory;
1295   GFile *file;
1296
1297   if (response == GTK_RESPONSE_OK)
1298     {
1299       GFile *parent;
1300       GFileInfo *info;
1301       guint64 free_space, file_size;
1302       GError *error = NULL;
1303
1304       file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (dialog));
1305       parent = g_file_get_parent (file);
1306       info = g_file_query_filesystem_info (parent,
1307           G_FILE_ATTRIBUTE_FILESYSTEM_FREE, NULL, &error);
1308
1309       g_object_unref (parent);
1310
1311       if (error != NULL)
1312         {
1313           g_warning ("Error: %s", error->message);
1314
1315           g_object_unref (file);
1316           return;
1317         }
1318
1319       free_space = g_file_info_get_attribute_uint64 (info,
1320           G_FILE_ATTRIBUTE_FILESYSTEM_FREE);
1321       file_size = empathy_ft_handler_get_total_bytes (handler);
1322
1323       g_object_unref (info);
1324
1325       if (file_size > free_space)
1326         {
1327           GtkWidget *message = gtk_message_dialog_new (GTK_WINDOW (dialog),
1328             GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR,
1329             GTK_BUTTONS_CLOSE,
1330             _("Insufficient free space to save file"));
1331           char *file_size_str, *free_space_str;
1332
1333           file_size_str = g_format_size (file_size);
1334           free_space_str = g_format_size (free_space);
1335
1336           gtk_message_dialog_format_secondary_text (
1337               GTK_MESSAGE_DIALOG (message),
1338               _("%s of free space are required to save this "
1339                 "file, but only %s is available. Please "
1340                 "choose another location."),
1341             file_size_str, free_space_str);
1342
1343           gtk_dialog_run (GTK_DIALOG (message));
1344
1345           g_free (file_size_str);
1346           g_free (free_space_str);
1347           gtk_widget_destroy (message);
1348
1349           g_object_unref (file);
1350
1351           return;
1352         }
1353
1354       factory = empathy_ft_factory_dup_singleton ();
1355
1356       empathy_ft_factory_set_destination_for_incoming_handler (
1357           factory, handler, file);
1358
1359       g_object_unref (factory);
1360       g_object_unref (file);
1361     }
1362   else
1363     {
1364       /* unref the handler, as we dismissed the file chooser,
1365        * and refused the transfer.
1366        */
1367       g_object_unref (handler);
1368     }
1369
1370   gtk_widget_destroy (GTK_WIDGET (dialog));
1371 }
1372
1373 void
1374 empathy_receive_file_with_file_chooser (EmpathyFTHandler *handler)
1375 {
1376   GtkWidget *widget;
1377   const gchar *dir;
1378   EmpathyContact *contact;
1379   gchar *title;
1380
1381   contact = empathy_ft_handler_get_contact (handler);
1382   g_assert (contact != NULL);
1383
1384   title = g_strdup_printf (_("Incoming file from %s"),
1385     empathy_contact_get_alias (contact));
1386
1387   widget = gtk_file_chooser_dialog_new (title,
1388       NULL, GTK_FILE_CHOOSER_ACTION_SAVE,
1389       GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
1390       GTK_STOCK_SAVE, GTK_RESPONSE_OK,
1391       NULL);
1392
1393   gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (widget),
1394     empathy_ft_handler_get_filename (handler));
1395
1396   gtk_file_chooser_set_do_overwrite_confirmation
1397     (GTK_FILE_CHOOSER (widget), TRUE);
1398
1399   dir = g_get_user_special_dir (G_USER_DIRECTORY_DOWNLOAD);
1400   if (dir == NULL)
1401     /* Fallback to $HOME if $XDG_DOWNLOAD_DIR is not set */
1402     dir = g_get_home_dir ();
1403
1404   gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (widget), dir);
1405
1406   g_signal_connect (widget, "response",
1407       G_CALLBACK (file_manager_receive_file_response_cb), handler);
1408
1409   gtk_widget_show (widget);
1410   g_free (title);
1411 }
1412
1413 void
1414 empathy_make_color_whiter (GdkRGBA *color)
1415 {
1416   const GdkRGBA white = { 1.0, 1.0, 1.0, 1.0 };
1417
1418   color->red = (color->red + white.red) / 2;
1419   color->green = (color->green + white.green) / 2;
1420   color->blue = (color->blue + white.blue) / 2;
1421 }
1422
1423 static void
1424 menu_deactivate_cb (GtkMenu *menu,
1425   gpointer user_data)
1426 {
1427   /* FIXME: we shouldn't have to disconnect the signal (bgo #641327) */
1428   g_signal_handlers_disconnect_by_func (menu,
1429          menu_deactivate_cb, user_data);
1430
1431   gtk_menu_detach (menu);
1432 }
1433
1434 /* Convenient function to create a GtkMenu attached to @attach_to and detach
1435  * it when the menu is not displayed any more. This is useful when creating a
1436  * context menu that we want to get rid as soon as it as been displayed. */
1437 GtkWidget *
1438 empathy_context_menu_new (GtkWidget *attach_to)
1439 {
1440   GtkWidget *menu;
1441
1442   menu = gtk_menu_new ();
1443
1444   gtk_menu_attach_to_widget (GTK_MENU (menu), attach_to, NULL);
1445
1446   /* menu is initially unowned but gtk_menu_attach_to_widget () taked its
1447    * floating ref. We can either wait that @attach_to releases its ref when
1448    * it will be destroyed (when leaving Empathy most of the time) or explicitely
1449    * detach the menu when it's not displayed any more.
1450    * We go for the latter as we don't want to keep useless menus in memory
1451    * during the whole lifetime of Empathy. */
1452   g_signal_connect (menu, "deactivate", G_CALLBACK (menu_deactivate_cb), NULL);
1453
1454   return menu;
1455 }
1456
1457 gint64
1458 empathy_get_current_action_time (void)
1459 {
1460   return (tp_user_action_time_from_x11 (gtk_get_current_event_time ()));
1461 }
1462
1463 /* @words = empathy_live_search_strip_utf8_string (@text);
1464  *
1465  * User has to pass both so we don't have to compute @words ourself each time
1466  * this function is called. */
1467 gboolean
1468 empathy_individual_match_string (FolksIndividual *individual,
1469     const char *text,
1470     GPtrArray *words)
1471 {
1472   const gchar *str;
1473   GeeSet *personas;
1474   GeeIterator *iter;
1475   gboolean retval = FALSE;
1476
1477   /* check alias name */
1478   str = folks_alias_details_get_alias (FOLKS_ALIAS_DETAILS (individual));
1479
1480   if (empathy_live_search_match_words (str, words))
1481     return TRUE;
1482
1483   personas = folks_individual_get_personas (individual);
1484
1485   /* check contact id, remove the @server.com part */
1486   iter = gee_iterable_iterator (GEE_ITERABLE (personas));
1487   while (retval == FALSE && gee_iterator_next (iter))
1488     {
1489       FolksPersona *persona = gee_iterator_get (iter);
1490       const gchar *p;
1491
1492       if (empathy_folks_persona_is_interesting (persona))
1493         {
1494           str = folks_persona_get_display_id (persona);
1495
1496           /* Accept the persona if @text is a full prefix of his ID; that allows
1497            * user to find, say, a jabber contact by typing his JID. */
1498           if (g_str_has_prefix (str, text))
1499             {
1500               retval = TRUE;
1501             }
1502           else
1503             {
1504               gchar *dup_str = NULL;
1505               gboolean visible;
1506
1507               p = strstr (str, "@");
1508               if (p != NULL)
1509                 str = dup_str = g_strndup (str, p - str);
1510
1511               visible = empathy_live_search_match_words (str, words);
1512               g_free (dup_str);
1513               if (visible)
1514                 retval = TRUE;
1515             }
1516         }
1517       g_clear_object (&persona);
1518     }
1519   g_clear_object (&iter);
1520
1521   /* FIXME: Add more rules here, we could check phone numbers in
1522    * contact's vCard for example. */
1523   return retval;
1524 }
1525
1526 void
1527 empathy_launch_program (const gchar *dir,
1528     const gchar *name,
1529     const gchar *args)
1530 {
1531   GdkDisplay *display;
1532   GError *error = NULL;
1533   gchar *path, *cmd;
1534   GAppInfo *app_info;
1535   GdkAppLaunchContext *context = NULL;
1536
1537   /* Try to run from source directory if possible */
1538   path = g_build_filename (g_getenv ("EMPATHY_SRCDIR"), "src",
1539       name, NULL);
1540
1541   if (!g_file_test (path, G_FILE_TEST_EXISTS))
1542     {
1543       g_free (path);
1544       path = g_build_filename (dir, name, NULL);
1545     }
1546
1547   if (args != NULL)
1548     cmd = g_strconcat (path, " ", args, NULL);
1549   else
1550     cmd = g_strdup (path);
1551
1552   app_info = g_app_info_create_from_commandline (cmd, NULL, 0, &error);
1553   if (app_info == NULL)
1554     {
1555       DEBUG ("Failed to create app info: %s", error->message);
1556       g_error_free (error);
1557       goto out;
1558     }
1559
1560   display = gdk_display_get_default ();
1561   context = gdk_display_get_app_launch_context (display);
1562
1563   if (!g_app_info_launch (app_info, NULL, (GAppLaunchContext *) context,
1564       &error))
1565     {
1566       g_warning ("Failed to launch %s: %s", name, error->message);
1567       g_error_free (error);
1568       goto out;
1569     }
1570
1571 out:
1572   tp_clear_object (&app_info);
1573   tp_clear_object (&context);
1574   g_free (path);
1575   g_free (cmd);
1576 }
1577
1578 /* Most of the workspace manipulation code has been copied from libwnck
1579  * Copyright (C) 2001 Havoc Pennington
1580  * Copyright (C) 2005-2007 Vincent Untz
1581  */
1582 static void
1583 _wnck_activate_workspace (Screen *screen,
1584     int new_active_space,
1585     Time timestamp)
1586 {
1587   Display *display;
1588   Window root;
1589   XEvent xev;
1590
1591   display = DisplayOfScreen (screen);
1592   root = RootWindowOfScreen (screen);
1593
1594   xev.xclient.type = ClientMessage;
1595   xev.xclient.serial = 0;
1596   xev.xclient.send_event = True;
1597   xev.xclient.display = display;
1598   xev.xclient.window = root;
1599   xev.xclient.message_type = gdk_x11_get_xatom_by_name ("_NET_CURRENT_DESKTOP");
1600   xev.xclient.format = 32;
1601   xev.xclient.data.l[0] = new_active_space;
1602   xev.xclient.data.l[1] = timestamp;
1603   xev.xclient.data.l[2] = 0;
1604   xev.xclient.data.l[3] = 0;
1605   xev.xclient.data.l[4] = 0;
1606
1607   gdk_error_trap_push ();
1608   XSendEvent (display, root, False,
1609       SubstructureRedirectMask | SubstructureNotifyMask,
1610       &xev);
1611   XSync (display, False);
1612   gdk_error_trap_pop_ignored ();
1613 }
1614
1615 static gboolean
1616 _wnck_get_cardinal (Screen *screen,
1617     Window xwindow,
1618     Atom atom,
1619     int *val)
1620 {
1621   Display *display;
1622   Atom type;
1623   int format;
1624   gulong nitems;
1625   gulong bytes_after;
1626   gulong *num;
1627   int err, result;
1628
1629   display = DisplayOfScreen (screen);
1630
1631   *val = 0;
1632
1633   gdk_error_trap_push ();
1634   type = None;
1635   result = XGetWindowProperty (display, xwindow, atom,
1636       0, G_MAXLONG, False, XA_CARDINAL, &type, &format, &nitems,
1637       &bytes_after, (void *) &num);
1638   err = gdk_error_trap_pop ();
1639   if (err != Success ||
1640       result != Success)
1641     return FALSE;
1642
1643   if (type != XA_CARDINAL)
1644     {
1645       XFree (num);
1646       return FALSE;
1647     }
1648
1649   *val = *num;
1650
1651   XFree (num);
1652
1653   return TRUE;
1654 }
1655
1656 static int
1657 window_get_workspace (Screen *xscreen,
1658     Window win)
1659 {
1660   int number;
1661
1662   if (!_wnck_get_cardinal (xscreen, win,
1663         gdk_x11_get_xatom_by_name ("_NET_WM_DESKTOP"), &number))
1664     return -1;
1665
1666   return number;
1667 }
1668
1669 /* Ask X to move to the desktop on which @window currently is
1670  * and the present @window. */
1671 void
1672 empathy_move_to_window_desktop (GtkWindow *window,
1673     guint32 timestamp)
1674 {
1675   GdkScreen *screen;
1676   Screen *xscreen;
1677   GdkWindow *gdk_window;
1678   int workspace;
1679
1680   screen = gtk_window_get_screen (window);
1681   xscreen = gdk_x11_screen_get_xscreen (screen);
1682   gdk_window = gtk_widget_get_window (GTK_WIDGET (window));
1683
1684   workspace = window_get_workspace (xscreen,
1685       gdk_x11_window_get_xid (gdk_window));
1686   if (workspace == -1)
1687     goto out;
1688
1689   _wnck_activate_workspace (xscreen, workspace, timestamp);
1690
1691 out:
1692   gtk_window_present_with_time (window, timestamp);
1693 }
1694
1695 void
1696 empathy_set_css_provider (GtkWidget *widget)
1697 {
1698   GtkCssProvider *provider;
1699   gchar *filename;
1700   GError *error = NULL;
1701   GdkScreen *screen;
1702
1703   filename = empathy_file_lookup ("empathy.css", "data");
1704
1705   provider = gtk_css_provider_new ();
1706
1707   if (!gtk_css_provider_load_from_path (provider, filename, &error))
1708     {
1709       g_warning ("Failed to load css file '%s': %s", filename, error->message);
1710       g_error_free (error);
1711       goto out;
1712     }
1713
1714   if (widget != NULL)
1715     screen = gtk_widget_get_screen (widget);
1716   else
1717     screen = gdk_screen_get_default ();
1718
1719   gtk_style_context_add_provider_for_screen (screen,
1720       GTK_STYLE_PROVIDER (provider),
1721       GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
1722
1723 out:
1724   g_free (filename);
1725   g_object_unref (provider);
1726 }