]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-ui-utils.c
Merge branch 'log-window-webview'
[empathy.git] / libempathy-gtk / empathy-ui-utils.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  * Copyright (C) 2002-2007 Imendio AB
4  * Copyright (C) 2007-2010 Collabora Ltd.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation; either version 2 of the
9  * License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public
17  * License along with this program; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA  02110-1301  USA
20  *
21  * Authors: Mikael Hallendal <micke@imendio.com>
22  *          Richard Hult <richard@imendio.com>
23  *          Martyn Russell <martyn@imendio.com>
24  *          Xavier Claessens <xclaesse@gmail.com>
25  *          Jonny Lamb <jonny.lamb@collabora.co.uk>
26  *          Travis Reitter <travis.reitter@collabora.co.uk>
27  *
28  *          Part of this file is copied from GtkSourceView (gtksourceiter.c):
29  *          Paolo Maggi
30  *          Jeroen Zwartepoorte
31  */
32
33 #include <config.h>
34
35 #include <string.h>
36 #include <X11/Xatom.h>
37 #include <gdk/gdkx.h>
38 #include <glib/gi18n-lib.h>
39 #include <gtk/gtk.h>
40 #include <gio/gio.h>
41
42 #include <telepathy-glib/util.h>
43 #include <folks/folks.h>
44
45 #include "empathy-ui-utils.h"
46 #include "empathy-images.h"
47 #include "empathy-live-search.h"
48 #include "empathy-smiley-manager.h"
49
50 #define DEBUG_FLAG EMPATHY_DEBUG_OTHER
51 #include <libempathy/empathy-debug.h>
52 #include <libempathy/empathy-utils.h>
53 #include <libempathy/empathy-ft-factory.h>
54
55 void
56 empathy_gtk_init (void)
57 {
58         static gboolean initialized = FALSE;
59
60         if (initialized)
61                 return;
62
63         empathy_init ();
64         gtk_icon_theme_append_search_path (gtk_icon_theme_get_default (),
65                                            PKGDATADIR G_DIR_SEPARATOR_S "icons");
66
67         initialized = TRUE;
68 }
69
70 static GtkBuilder *
71 builder_get_file_valist (const gchar *filename,
72                          const gchar *first_object,
73                          va_list      args)
74 {
75         GtkBuilder  *gui;
76         const gchar *name;
77         GObject    **object_ptr;
78         GError      *error = NULL;
79
80         DEBUG ("Loading file %s", filename);
81
82         gui = gtk_builder_new ();
83         gtk_builder_set_translation_domain (gui, GETTEXT_PACKAGE);
84         if (!gtk_builder_add_from_file (gui, filename, &error)) {
85                 g_critical ("GtkBuilder Error (%s): %s",
86                                 filename, error->message);
87                 g_clear_error (&error);
88                 g_object_unref (gui);
89
90                 /* we need to iterate and set all of the pointers to NULL */
91                 for (name = first_object; name;
92                      name = va_arg (args, const gchar *)) {
93                         object_ptr = va_arg (args, GObject**);
94
95                         *object_ptr = NULL;
96                 }
97
98                 return NULL;
99         }
100
101         for (name = first_object; name; name = va_arg (args, const gchar *)) {
102                 object_ptr = va_arg (args, GObject**);
103
104                 *object_ptr = gtk_builder_get_object (gui, name);
105
106                 if (!*object_ptr) {
107                         g_warning ("File is missing object '%s'.", name);
108                         continue;
109                 }
110         }
111
112         return gui;
113 }
114
115 GtkBuilder *
116 empathy_builder_get_file (const gchar *filename,
117                           const gchar *first_object,
118                           ...)
119 {
120         GtkBuilder *gui;
121         va_list     args;
122
123         va_start (args, first_object);
124         gui = builder_get_file_valist (filename, first_object, args);
125         va_end (args);
126
127         return gui;
128 }
129
130 void
131 empathy_builder_connect (GtkBuilder  *gui,
132                          gpointer     user_data,
133                          const gchar *first_object,
134                          ...)
135 {
136         va_list      args;
137         const gchar *name;
138         const gchar *sig;
139         GObject     *object;
140         GCallback    callback;
141
142         va_start (args, first_object);
143         for (name = first_object; name; name = va_arg (args, const gchar *)) {
144                 sig = va_arg (args, const gchar *);
145                 callback = va_arg (args, GCallback);
146
147                 object = gtk_builder_get_object (gui, name);
148                 if (!object) {
149                         g_warning ("File is missing object '%s'.", name);
150                         continue;
151                 }
152
153                 g_signal_connect (object, sig, callback, user_data);
154         }
155
156         va_end (args);
157 }
158
159 GtkWidget *
160 empathy_builder_unref_and_keep_widget (GtkBuilder *gui,
161                                        GtkWidget  *widget)
162 {
163         /* On construction gui sinks the initial reference to widget. When gui
164          * is finalized it will drop its ref to widget. We take our own ref to
165          * prevent widget being finalised. The widget is forced to have a
166          * floating reference, like when it was initially unowned so that it can
167          * be used like any other GtkWidget. */
168
169         g_object_ref (widget);
170         g_object_force_floating (G_OBJECT (widget));
171         g_object_unref (gui);
172
173         return widget;
174 }
175
176 const gchar *
177 empathy_icon_name_for_presence (TpConnectionPresenceType presence)
178 {
179         switch (presence) {
180         case TP_CONNECTION_PRESENCE_TYPE_AVAILABLE:
181                 return EMPATHY_IMAGE_AVAILABLE;
182         case TP_CONNECTION_PRESENCE_TYPE_BUSY:
183                 return EMPATHY_IMAGE_BUSY;
184         case TP_CONNECTION_PRESENCE_TYPE_AWAY:
185                 return EMPATHY_IMAGE_AWAY;
186         case TP_CONNECTION_PRESENCE_TYPE_EXTENDED_AWAY:
187                 if (gtk_icon_theme_has_icon (gtk_icon_theme_get_default (),
188                                              EMPATHY_IMAGE_EXT_AWAY))
189                         return EMPATHY_IMAGE_EXT_AWAY;
190
191                 /* The 'extended-away' icon is not an official one so we fallback to idle if
192                  * it's not implemented */
193                 return EMPATHY_IMAGE_IDLE;
194         case TP_CONNECTION_PRESENCE_TYPE_HIDDEN:
195                 if (gtk_icon_theme_has_icon (gtk_icon_theme_get_default (),
196                                              EMPATHY_IMAGE_HIDDEN))
197                         return EMPATHY_IMAGE_HIDDEN;
198
199                 /* The 'hidden' icon is not an official one so we fallback to offline if
200                  * it's not implemented */
201                 return EMPATHY_IMAGE_OFFLINE;
202         case TP_CONNECTION_PRESENCE_TYPE_OFFLINE:
203         case TP_CONNECTION_PRESENCE_TYPE_ERROR:
204                 return EMPATHY_IMAGE_OFFLINE;
205         case TP_CONNECTION_PRESENCE_TYPE_UNKNOWN:
206                 return EMPATHY_IMAGE_PENDING;
207         case TP_CONNECTION_PRESENCE_TYPE_UNSET:
208         default:
209                 return NULL;
210         }
211
212         return NULL;
213 }
214
215 const gchar *
216 empathy_icon_name_for_contact (EmpathyContact *contact)
217 {
218         TpConnectionPresenceType presence;
219
220         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact),
221                               EMPATHY_IMAGE_OFFLINE);
222
223         presence = empathy_contact_get_presence (contact);
224         return empathy_icon_name_for_presence (presence);
225 }
226
227 const gchar *
228 empathy_icon_name_for_individual (FolksIndividual *individual)
229 {
230         FolksPresenceType folks_presence;
231         TpConnectionPresenceType presence;
232
233         folks_presence =
234             folks_presence_details_get_presence_type (
235                 FOLKS_PRESENCE_DETAILS (individual));
236         presence = empathy_folks_presence_type_to_tp (folks_presence);
237
238         return empathy_icon_name_for_presence (presence);
239 }
240
241 const gchar *
242 empathy_protocol_name_for_contact (EmpathyContact   *contact)
243 {
244         TpAccount     *account;
245
246         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
247
248         account = empathy_contact_get_account (contact);
249         if (account == NULL) {
250                 return NULL;
251         }
252
253         return tp_account_get_icon_name (account);
254 }
255
256 GdkPixbuf *
257 empathy_pixbuf_from_data (gchar *data,
258                           gsize  data_size)
259 {
260         return empathy_pixbuf_from_data_and_mime (data, data_size, NULL);
261 }
262
263 GdkPixbuf *
264 empathy_pixbuf_from_data_and_mime (gchar  *data,
265                                    gsize   data_size,
266                                    gchar **mime_type)
267 {
268         GdkPixbufLoader *loader;
269         GdkPixbufFormat *format;
270         GdkPixbuf       *pixbuf = NULL;
271         gchar          **mime_types;
272         GError          *error = NULL;
273
274         if (!data) {
275                 return NULL;
276         }
277
278         loader = gdk_pixbuf_loader_new ();
279         if (!gdk_pixbuf_loader_write (loader, (guchar *) data, data_size, &error)) {
280                 DEBUG ("Failed to write to pixbuf loader: %s",
281                         error ? error->message : "No error given");
282                 goto out;
283         }
284         if (!gdk_pixbuf_loader_close (loader, &error)) {
285                 DEBUG ("Failed to close pixbuf loader: %s",
286                         error ? error->message : "No error given");
287                 goto out;
288         }
289
290         pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
291         if (pixbuf) {
292                 g_object_ref (pixbuf);
293
294                 if (mime_type != NULL) {
295                         format = gdk_pixbuf_loader_get_format (loader);
296                         mime_types = gdk_pixbuf_format_get_mime_types (format);
297
298                         *mime_type = g_strdup (*mime_types);
299                         if (mime_types[1] != NULL) {
300                                 DEBUG ("Loader supports more than one mime "
301                                         "type! Picking the first one, %s",
302                                         *mime_type);
303                         }
304                         g_strfreev (mime_types);
305                 }
306         }
307
308 out:
309         g_clear_error (&error);
310         g_object_unref (loader);
311
312         return pixbuf;
313 }
314
315 struct SizeData {
316         gint     width;
317         gint     height;
318         gboolean preserve_aspect_ratio;
319 };
320
321 static void
322 pixbuf_from_avatar_size_prepared_cb (GdkPixbufLoader *loader,
323                                      int              width,
324                                      int              height,
325                                      struct SizeData *data)
326 {
327         g_return_if_fail (width > 0 && height > 0);
328
329         if (data->preserve_aspect_ratio && (data->width > 0 || data->height > 0)) {
330                 if (width < data->width && height < data->height) {
331                         width = width;
332                         height = height;
333                 }
334
335                 if (data->width < 0) {
336                         width = width * (double) data->height / (gdouble) height;
337                         height = data->height;
338                 } else if (data->height < 0) {
339                         height = height * (double) data->width / (double) width;
340                         width = data->width;
341                 } else if ((double) height * (double) data->width >
342                            (double) width * (double) data->height) {
343                         width = 0.5 + (double) width * (double) data->height / (double) height;
344                         height = data->height;
345                 } else {
346                         height = 0.5 + (double) height * (double) data->width / (double) width;
347                         width = data->width;
348                 }
349         } else {
350                 if (data->width > 0) {
351                         width = data->width;
352                 }
353
354                 if (data->height > 0) {
355                         height = data->height;
356                 }
357         }
358
359         gdk_pixbuf_loader_set_size (loader, width, height);
360 }
361
362 static void
363 empathy_avatar_pixbuf_roundify (GdkPixbuf *pixbuf)
364 {
365         gint width, height, rowstride;
366         guchar *pixels;
367
368         width = gdk_pixbuf_get_width (pixbuf);
369         height = gdk_pixbuf_get_height (pixbuf);
370         rowstride = gdk_pixbuf_get_rowstride (pixbuf);
371         pixels = gdk_pixbuf_get_pixels (pixbuf);
372
373         if (width < 6 || height < 6) {
374                 return;
375         }
376
377         /* Top left */
378         pixels[3] = 0;
379         pixels[7] = 0x80;
380         pixels[11] = 0xC0;
381         pixels[rowstride + 3] = 0x80;
382         pixels[rowstride * 2 + 3] = 0xC0;
383
384         /* Top right */
385         pixels[width * 4 - 1] = 0;
386         pixels[width * 4 - 5] = 0x80;
387         pixels[width * 4 - 9] = 0xC0;
388         pixels[rowstride + (width * 4) - 1] = 0x80;
389         pixels[(2 * rowstride) + (width * 4) - 1] = 0xC0;
390
391         /* Bottom left */
392         pixels[(height - 1) * rowstride + 3] = 0;
393         pixels[(height - 1) * rowstride + 7] = 0x80;
394         pixels[(height - 1) * rowstride + 11] = 0xC0;
395         pixels[(height - 2) * rowstride + 3] = 0x80;
396         pixels[(height - 3) * rowstride + 3] = 0xC0;
397
398         /* Bottom right */
399         pixels[height * rowstride - 1] = 0;
400         pixels[(height - 1) * rowstride - 1] = 0x80;
401         pixels[(height - 2) * rowstride - 1] = 0xC0;
402         pixels[height * rowstride - 5] = 0x80;
403         pixels[height * rowstride - 9] = 0xC0;
404 }
405
406 static gboolean
407 empathy_gdk_pixbuf_is_opaque (GdkPixbuf *pixbuf)
408 {
409         gint height, rowstride, i;
410         guchar *pixels;
411         guchar *row;
412
413         height = gdk_pixbuf_get_height (pixbuf);
414         rowstride = gdk_pixbuf_get_rowstride (pixbuf);
415         pixels = gdk_pixbuf_get_pixels (pixbuf);
416
417         row = pixels;
418         for (i = 3; i < rowstride; i+=4) {
419                 if (row[i] < 0xfe) {
420                         return FALSE;
421                 }
422         }
423
424         for (i = 1; i < height - 1; i++) {
425                 row = pixels + (i*rowstride);
426                 if (row[3] < 0xfe || row[rowstride-1] < 0xfe) {
427                         return FALSE;
428                 }
429         }
430
431         row = pixels + ((height-1) * rowstride);
432         for (i = 3; i < rowstride; i+=4) {
433                 if (row[i] < 0xfe) {
434                         return FALSE;
435                 }
436         }
437
438         return TRUE;
439 }
440
441 static GdkPixbuf *
442 avatar_pixbuf_from_loader (GdkPixbufLoader *loader)
443 {
444         GdkPixbuf *pixbuf;
445
446         pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
447         if (!gdk_pixbuf_get_has_alpha (pixbuf)) {
448                 GdkPixbuf *rounded_pixbuf;
449
450                 rounded_pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8,
451                                                  gdk_pixbuf_get_width (pixbuf),
452                                                  gdk_pixbuf_get_height (pixbuf));
453                 gdk_pixbuf_copy_area (pixbuf, 0, 0,
454                                       gdk_pixbuf_get_width (pixbuf),
455                                       gdk_pixbuf_get_height (pixbuf),
456                                       rounded_pixbuf,
457                                       0, 0);
458                 pixbuf = rounded_pixbuf;
459         } else {
460                 g_object_ref (pixbuf);
461         }
462
463         if (empathy_gdk_pixbuf_is_opaque (pixbuf)) {
464                 empathy_avatar_pixbuf_roundify (pixbuf);
465         }
466
467         return pixbuf;
468 }
469
470 GdkPixbuf *
471 empathy_pixbuf_from_avatar_scaled (EmpathyAvatar *avatar,
472                                   gint          width,
473                                   gint          height)
474 {
475         GdkPixbuf        *pixbuf;
476         GdkPixbufLoader  *loader;
477         struct SizeData   data;
478         GError           *error = NULL;
479
480         if (!avatar) {
481                 return NULL;
482         }
483
484         data.width = width;
485         data.height = height;
486         data.preserve_aspect_ratio = TRUE;
487
488         loader = gdk_pixbuf_loader_new ();
489
490         g_signal_connect (loader, "size-prepared",
491                           G_CALLBACK (pixbuf_from_avatar_size_prepared_cb),
492                           &data);
493
494         if (!gdk_pixbuf_loader_write (loader, avatar->data, avatar->len, &error)) {
495                 g_warning ("Couldn't write avatar image:%p with "
496                            "length:%" G_GSIZE_FORMAT " to pixbuf loader: %s",
497                            avatar->data, avatar->len, error->message);
498                 g_error_free (error);
499                 return NULL;
500         }
501
502         gdk_pixbuf_loader_close (loader, NULL);
503         pixbuf = avatar_pixbuf_from_loader (loader);
504
505         g_object_unref (loader);
506
507         return pixbuf;
508 }
509
510 GdkPixbuf *
511 empathy_pixbuf_avatar_from_contact_scaled (EmpathyContact *contact,
512                                           gint           width,
513                                           gint           height)
514 {
515         EmpathyAvatar *avatar;
516
517         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
518
519         avatar = empathy_contact_get_avatar (contact);
520
521         return empathy_pixbuf_from_avatar_scaled (avatar, width, height);
522 }
523
524 typedef struct {
525         FolksIndividual *individual;
526         GSimpleAsyncResult *result;
527         guint width;
528         guint height;
529         struct SizeData size_data;
530         GdkPixbufLoader *loader;
531         GCancellable *cancellable;
532         guint8 data[512];
533 } PixbufAvatarFromIndividualClosure;
534
535 static PixbufAvatarFromIndividualClosure *
536 pixbuf_avatar_from_individual_closure_new (FolksIndividual    *individual,
537                                            GSimpleAsyncResult *result,
538                                            gint                width,
539                                            gint                height,
540                                            GCancellable       *cancellable)
541 {
542         PixbufAvatarFromIndividualClosure *closure;
543
544         g_return_val_if_fail (FOLKS_IS_INDIVIDUAL (individual), NULL);
545         g_return_val_if_fail (G_IS_ASYNC_RESULT (result), NULL);
546
547         closure = g_new0 (PixbufAvatarFromIndividualClosure, 1);
548         closure->individual = g_object_ref (individual);
549         closure->result = g_object_ref (result);
550         closure->width = width;
551         closure->height = height;
552         closure->cancellable = g_object_ref (cancellable);
553
554         return closure;
555 }
556
557 static void
558 pixbuf_avatar_from_individual_closure_free (
559                 PixbufAvatarFromIndividualClosure *closure)
560 {
561         g_object_unref (closure->cancellable);
562         tp_clear_object (&closure->loader);
563         g_object_unref (closure->individual);
564         g_object_unref (closure->result);
565         g_free (closure);
566 }
567
568 static void
569 avatar_icon_load_read_cb (GObject      *object,
570                           GAsyncResult *result,
571                           gpointer      user_data)
572 {
573         GInputStream *stream = G_INPUT_STREAM (object);
574         PixbufAvatarFromIndividualClosure *closure = user_data;
575         gssize n_read;
576         GError *error = NULL;
577
578         /* Finish reading this chunk from the stream */
579         n_read = g_input_stream_read_finish (stream, result, &error);
580         if (error != NULL) {
581                 DEBUG ("Failed to finish read from pixbuf stream: %s",
582                         error->message);
583                 g_simple_async_result_set_from_error (closure->result, error);
584                 goto out_close;
585         }
586
587         /* Write the chunk to the pixbuf loader */
588         if (!gdk_pixbuf_loader_write (closure->loader, (guchar *) closure->data,
589                         n_read, &error)) {
590                 DEBUG ("Failed to write to pixbuf loader: %s",
591                         error ? error->message : "No error given");
592                 g_simple_async_result_set_from_error (closure->result, error);
593                 goto out_close;
594         }
595
596         if (n_read == 0) {
597                 /* EOF? */
598                 if (!gdk_pixbuf_loader_close (closure->loader, &error)) {
599                         DEBUG ("Failed to close pixbuf loader: %s",
600                                 error ? error->message : "No error given");
601                         g_simple_async_result_set_from_error (closure->result, error);
602                         goto out;
603                 }
604
605                 /* We're done. */
606                 g_simple_async_result_set_op_res_gpointer (closure->result,
607                         avatar_pixbuf_from_loader (closure->loader),
608                         g_object_unref);
609
610                 goto out;
611         } else {
612                 /* Loop round and read another chunk. */
613                 g_input_stream_read_async (stream, closure->data,
614                         G_N_ELEMENTS (closure->data),
615                         G_PRIORITY_DEFAULT, closure->cancellable,
616                         avatar_icon_load_read_cb, closure);
617
618                 return;
619         }
620
621 out_close:
622         /* We must close the pixbuf loader before unreffing it. */
623         gdk_pixbuf_loader_close (closure->loader, NULL);
624
625 out:
626         g_simple_async_result_complete (closure->result);
627
628         g_clear_error (&error);
629         pixbuf_avatar_from_individual_closure_free (closure);
630 }
631
632 static void
633 avatar_icon_load_cb (GObject      *object,
634                      GAsyncResult *result,
635                      gpointer      user_data)
636 {
637         GLoadableIcon *icon = G_LOADABLE_ICON (object);
638         PixbufAvatarFromIndividualClosure *closure = user_data;
639         GInputStream *stream;
640         GError *error = NULL;
641
642         stream = g_loadable_icon_load_finish (icon, result, NULL, &error);
643         if (error != NULL) {
644                 DEBUG ("Failed to open avatar stream: %s", error->message);
645                 g_simple_async_result_set_from_error (closure->result, error);
646                 goto out;
647         }
648
649         closure->size_data.width = closure->width;
650         closure->size_data.height = closure->height;
651         closure->size_data.preserve_aspect_ratio = TRUE;
652
653         /* Load the data into a pixbuf loader in chunks. */
654         closure->loader = gdk_pixbuf_loader_new ();
655
656         g_signal_connect (closure->loader, "size-prepared",
657                           G_CALLBACK (pixbuf_from_avatar_size_prepared_cb),
658                           &(closure->size_data));
659
660         /* Begin to read the first chunk. */
661         g_input_stream_read_async (stream, closure->data,
662                         G_N_ELEMENTS (closure->data),
663                         G_PRIORITY_DEFAULT, closure->cancellable,
664                         avatar_icon_load_read_cb, closure);
665
666         g_object_unref (stream);
667
668         return;
669
670 out:
671         g_simple_async_result_complete (closure->result);
672
673         g_clear_error (&error);
674         tp_clear_object (&stream);
675         pixbuf_avatar_from_individual_closure_free (closure);
676 }
677
678 void
679 empathy_pixbuf_avatar_from_individual_scaled_async (
680                 FolksIndividual     *individual,
681                 gint                 width,
682                 gint                 height,
683                 GCancellable        *cancellable,
684                 GAsyncReadyCallback  callback,
685                 gpointer             user_data)
686 {
687         GLoadableIcon *avatar_icon;
688         GSimpleAsyncResult *result;
689         PixbufAvatarFromIndividualClosure *closure;
690
691         result = g_simple_async_result_new (G_OBJECT (individual),
692                         callback, user_data,
693                         empathy_pixbuf_avatar_from_individual_scaled_async);
694
695         avatar_icon =
696                 folks_avatar_details_get_avatar (FOLKS_AVATAR_DETAILS (individual));
697         if (avatar_icon == NULL)
698                 goto out;
699
700         closure = pixbuf_avatar_from_individual_closure_new (individual, result,
701                                                              width, height,
702                                                              cancellable);
703         if (closure == NULL)
704                 goto out;
705
706         g_loadable_icon_load_async (avatar_icon, width, cancellable,
707                         avatar_icon_load_cb, closure);
708
709         g_object_unref (result);
710
711         return;
712
713 out:
714         g_simple_async_result_set_op_res_gpointer (result, NULL, NULL);
715         g_simple_async_result_complete (result);
716         g_object_unref (result);
717 }
718
719 /* Return a ref on the GdkPixbuf */
720 GdkPixbuf *
721 empathy_pixbuf_avatar_from_individual_scaled_finish (
722                 FolksIndividual *individual,
723                 GAsyncResult *result,
724                 GError **error)
725 {
726         GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
727         gboolean result_valid;
728         GdkPixbuf *pixbuf;
729
730         g_return_val_if_fail (FOLKS_IS_INDIVIDUAL (individual), NULL);
731         g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), NULL);
732
733         if (g_simple_async_result_propagate_error (simple, error))
734                 return NULL;
735
736         result_valid = g_simple_async_result_is_valid (result,
737                         G_OBJECT (individual),
738                         empathy_pixbuf_avatar_from_individual_scaled_async);
739         g_return_val_if_fail (result_valid, NULL);
740
741         pixbuf = g_simple_async_result_get_op_res_gpointer (simple);
742         return pixbuf != NULL ? g_object_ref (pixbuf) : NULL;
743 }
744
745 GdkPixbuf *
746 empathy_pixbuf_contact_status_icon (EmpathyContact *contact,
747                                    gboolean       show_protocol)
748 {
749         const gchar *icon_name;
750
751         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
752
753         icon_name = empathy_icon_name_for_contact (contact);
754
755         if (icon_name == NULL) {
756                 return NULL;
757         }
758         return empathy_pixbuf_contact_status_icon_with_icon_name (contact,
759             icon_name,
760             show_protocol);
761 }
762
763 GdkPixbuf *
764 empathy_pixbuf_contact_status_icon_with_icon_name (EmpathyContact *contact,
765                                           const gchar    *icon_name,
766                                           gboolean       show_protocol)
767 {
768         GdkPixbuf *pix_status;
769         GdkPixbuf *pix_protocol;
770         gchar     *icon_filename;
771         gint       height, width;
772         gint       numerator, denominator;
773
774         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact) ||
775                         (show_protocol == FALSE), NULL);
776         g_return_val_if_fail (icon_name != NULL, NULL);
777
778         numerator = 3;
779         denominator = 4;
780
781         icon_filename = empathy_filename_from_icon_name (icon_name,
782                                                          GTK_ICON_SIZE_MENU);
783         if (icon_filename == NULL) {
784                 DEBUG ("icon name: %s could not be found\n", icon_name);
785                 return NULL;
786         }
787
788         pix_status = gdk_pixbuf_new_from_file (icon_filename, NULL);
789
790         if (pix_status == NULL) {
791                 DEBUG ("Could not open icon %s\n", icon_filename);
792                 g_free (icon_filename);
793                 return NULL;
794         }
795
796         g_free (icon_filename);
797
798         if (!show_protocol)
799                 return pix_status;
800
801         height = gdk_pixbuf_get_height (pix_status);
802         width = gdk_pixbuf_get_width (pix_status);
803
804         pix_protocol = empathy_pixbuf_protocol_from_contact_scaled (contact,
805                                                                     width * numerator / denominator,
806                                                                     height * numerator / denominator);
807
808         if (pix_protocol == NULL) {
809                 return pix_status;
810         }
811         gdk_pixbuf_composite (pix_protocol, pix_status,
812             0, height - height * numerator / denominator,
813             width * numerator / denominator, height * numerator / denominator,
814             0, height - height * numerator / denominator,
815             1, 1,
816             GDK_INTERP_BILINEAR, 255);
817
818         g_object_unref (pix_protocol);
819
820         return pix_status;
821 }
822
823 GdkPixbuf *
824 empathy_pixbuf_protocol_from_contact_scaled (EmpathyContact *contact,
825                                           gint           width,
826                                           gint           height)
827 {
828         TpAccount *account;
829         gchar     *filename;
830         GdkPixbuf *pixbuf = NULL;
831
832         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
833
834         account = empathy_contact_get_account (contact);
835         filename = empathy_filename_from_icon_name (tp_account_get_icon_name (account),
836                                                     GTK_ICON_SIZE_MENU);
837         if (filename != NULL) {
838                 pixbuf = gdk_pixbuf_new_from_file_at_size (filename, width, height, NULL);
839                 g_free (filename);
840         }
841
842         return pixbuf;
843 }
844
845 GdkPixbuf *
846 empathy_pixbuf_scale_down_if_necessary (GdkPixbuf *pixbuf, gint max_size)
847 {
848         gint      width, height;
849         gdouble   factor;
850
851         width = gdk_pixbuf_get_width (pixbuf);
852         height = gdk_pixbuf_get_height (pixbuf);
853
854         if (width > 0 && (width > max_size || height > max_size)) {
855                 factor = (gdouble) max_size / MAX (width, height);
856
857                 width = width * factor;
858                 height = height * factor;
859
860                 return gdk_pixbuf_scale_simple (pixbuf,
861                                                 width, height,
862                                                 GDK_INTERP_HYPER);
863         }
864
865         return g_object_ref (pixbuf);
866 }
867
868 GdkPixbuf *
869 empathy_pixbuf_from_icon_name_sized (const gchar *icon_name,
870                                      gint size)
871 {
872         GtkIconTheme *theme;
873         GdkPixbuf *pixbuf;
874         GError *error = NULL;
875
876         if (!icon_name) {
877                 return NULL;
878         }
879
880         theme = gtk_icon_theme_get_default ();
881
882         pixbuf = gtk_icon_theme_load_icon (theme,
883                                            icon_name,
884                                            size,
885                                            0,
886                                            &error);
887         if (error) {
888                 DEBUG ("Error loading icon: %s", error->message);
889                 g_clear_error (&error);
890         }
891
892         return pixbuf;
893 }
894
895 GdkPixbuf *
896 empathy_pixbuf_from_icon_name (const gchar *icon_name,
897                                GtkIconSize  icon_size)
898 {
899         gint  w, h;
900         gint  size = 48;
901
902         if (!icon_name) {
903                 return NULL;
904         }
905
906         if (gtk_icon_size_lookup (icon_size, &w, &h)) {
907                 size = (w + h) / 2;
908         }
909
910         return empathy_pixbuf_from_icon_name_sized (icon_name, size);
911 }
912
913 gchar *
914 empathy_filename_from_icon_name (const gchar *icon_name,
915                                  GtkIconSize  icon_size)
916 {
917         GtkIconTheme *icon_theme;
918         GtkIconInfo  *icon_info;
919         gint          w, h;
920         gint          size = 48;
921         gchar        *ret;
922
923         icon_theme = gtk_icon_theme_get_default ();
924
925         if (gtk_icon_size_lookup (icon_size, &w, &h)) {
926                 size = (w + h) / 2;
927         }
928
929         icon_info = gtk_icon_theme_lookup_icon (icon_theme, icon_name, size, 0);
930         ret = g_strdup (gtk_icon_info_get_filename (icon_info));
931         gtk_icon_info_free (icon_info);
932
933         return ret;
934 }
935
936 /* Stolen from GtkSourceView, hence the weird intendation. Please keep it like
937  * that to make it easier to apply changes from the original code.
938  */
939 #define GTK_TEXT_UNKNOWN_CHAR 0xFFFC
940
941 /* this function acts like g_utf8_offset_to_pointer() except that if it finds a
942  * decomposable character it consumes the decomposition length from the given
943  * offset.  So it's useful when the offset was calculated for the normalized
944  * version of str, but we need a pointer to str itself. */
945 static const gchar *
946 pointer_from_offset_skipping_decomp (const gchar *str, gint offset)
947 {
948         gchar *casefold, *normal;
949         const gchar *p, *q;
950
951         p = str;
952         while (offset > 0)
953         {
954                 q = g_utf8_next_char (p);
955                 casefold = g_utf8_casefold (p, q - p);
956                 normal = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
957                 offset -= g_utf8_strlen (normal, -1);
958                 g_free (casefold);
959                 g_free (normal);
960                 p = q;
961         }
962         return p;
963 }
964
965 static const gchar *
966 g_utf8_strcasestr (const gchar *haystack, const gchar *needle)
967 {
968         gsize needle_len;
969         gsize haystack_len;
970         const gchar *ret = NULL;
971         gchar *p;
972         gchar *casefold;
973         gchar *caseless_haystack;
974         gint i;
975
976         g_return_val_if_fail (haystack != NULL, NULL);
977         g_return_val_if_fail (needle != NULL, NULL);
978
979         casefold = g_utf8_casefold (haystack, -1);
980         caseless_haystack = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
981         g_free (casefold);
982
983         needle_len = g_utf8_strlen (needle, -1);
984         haystack_len = g_utf8_strlen (caseless_haystack, -1);
985
986         if (needle_len == 0)
987         {
988                 ret = (gchar *) haystack;
989                 goto finally_1;
990         }
991
992         if (haystack_len < needle_len)
993         {
994                 ret = NULL;
995                 goto finally_1;
996         }
997
998         p = (gchar *) caseless_haystack;
999         needle_len = strlen (needle);
1000         i = 0;
1001
1002         while (*p)
1003         {
1004                 if ((strncmp (p, needle, needle_len) == 0))
1005                 {
1006                         ret = pointer_from_offset_skipping_decomp (haystack, i);
1007                         goto finally_1;
1008                 }
1009
1010                 p = g_utf8_next_char (p);
1011                 i++;
1012         }
1013
1014 finally_1:
1015         g_free (caseless_haystack);
1016
1017         return ret;
1018 }
1019
1020 static gboolean
1021 g_utf8_caselessnmatch (const char *s1, const char *s2,
1022                        gssize n1, gssize n2)
1023 {
1024         gchar *casefold;
1025         gchar *normalized_s1;
1026         gchar *normalized_s2;
1027         gint len_s1;
1028         gint len_s2;
1029         gboolean ret = FALSE;
1030
1031         g_return_val_if_fail (s1 != NULL, FALSE);
1032         g_return_val_if_fail (s2 != NULL, FALSE);
1033         g_return_val_if_fail (n1 > 0, FALSE);
1034         g_return_val_if_fail (n2 > 0, FALSE);
1035
1036         casefold = g_utf8_casefold (s1, n1);
1037         normalized_s1 = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1038         g_free (casefold);
1039
1040         casefold = g_utf8_casefold (s2, n2);
1041         normalized_s2 = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1042         g_free (casefold);
1043
1044         len_s1 = strlen (normalized_s1);
1045         len_s2 = strlen (normalized_s2);
1046
1047         if (len_s1 < len_s2)
1048                 goto finally_2;
1049
1050         ret = (strncmp (normalized_s1, normalized_s2, len_s2) == 0);
1051
1052 finally_2:
1053         g_free (normalized_s1);
1054         g_free (normalized_s2);
1055
1056         return ret;
1057 }
1058
1059 static void
1060 forward_chars_with_skipping (GtkTextIter *iter,
1061                              gint         count,
1062                              gboolean     skip_invisible,
1063                              gboolean     skip_nontext,
1064                              gboolean     skip_decomp)
1065 {
1066         gint i;
1067
1068         g_return_if_fail (count >= 0);
1069
1070         i = count;
1071
1072         while (i > 0)
1073         {
1074                 gboolean ignored = FALSE;
1075
1076                 /* minimal workaround to avoid the infinite loop of bug #168247.
1077                  * It doesn't fix the problemjust the symptom...
1078                  */
1079                 if (gtk_text_iter_is_end (iter))
1080                         return;
1081
1082                 if (skip_nontext && gtk_text_iter_get_char (iter) == GTK_TEXT_UNKNOWN_CHAR)
1083                         ignored = TRUE;
1084
1085                 if (!ignored && skip_invisible &&
1086                     /* _gtk_text_btree_char_is_invisible (iter)*/ FALSE)
1087                         ignored = TRUE;
1088
1089                 if (!ignored && skip_decomp)
1090                 {
1091                         /* being UTF8 correct sucks; this accounts for extra
1092                            offsets coming from canonical decompositions of
1093                            UTF8 characters (e.g. accented characters) which
1094                            g_utf8_normalize () performs */
1095                         gchar *normal;
1096                         gchar buffer[6];
1097                         gint buffer_len;
1098
1099                         buffer_len = g_unichar_to_utf8 (gtk_text_iter_get_char (iter), buffer);
1100                         normal = g_utf8_normalize (buffer, buffer_len, G_NORMALIZE_NFD);
1101                         i -= (g_utf8_strlen (normal, -1) - 1);
1102                         g_free (normal);
1103                 }
1104
1105                 gtk_text_iter_forward_char (iter);
1106
1107                 if (!ignored)
1108                         --i;
1109         }
1110 }
1111
1112 static gboolean
1113 lines_match (const GtkTextIter *start,
1114              const gchar      **lines,
1115              gboolean           visible_only,
1116              gboolean           slice,
1117              GtkTextIter       *match_start,
1118              GtkTextIter       *match_end)
1119 {
1120         GtkTextIter next;
1121         gchar *line_text;
1122         const gchar *found;
1123         gint offset;
1124
1125         if (*lines == NULL || **lines == '\0')
1126         {
1127                 if (match_start)
1128                         *match_start = *start;
1129                 if (match_end)
1130                         *match_end = *start;
1131                 return TRUE;
1132         }
1133
1134         next = *start;
1135         gtk_text_iter_forward_line (&next);
1136
1137         /* No more text in buffer, but *lines is nonempty */
1138         if (gtk_text_iter_equal (start, &next))
1139                 return FALSE;
1140
1141         if (slice)
1142         {
1143                 if (visible_only)
1144                         line_text = gtk_text_iter_get_visible_slice (start, &next);
1145                 else
1146                         line_text = gtk_text_iter_get_slice (start, &next);
1147         }
1148         else
1149         {
1150                 if (visible_only)
1151                         line_text = gtk_text_iter_get_visible_text (start, &next);
1152                 else
1153                         line_text = gtk_text_iter_get_text (start, &next);
1154         }
1155
1156         if (match_start) /* if this is the first line we're matching */
1157         {
1158                 found = g_utf8_strcasestr (line_text, *lines);
1159         }
1160         else
1161         {
1162                 /* If it's not the first line, we have to match from the
1163                  * start of the line.
1164                  */
1165                 if (g_utf8_caselessnmatch (line_text, *lines, strlen (line_text),
1166                                            strlen (*lines)))
1167                         found = line_text;
1168                 else
1169                         found = NULL;
1170         }
1171
1172         if (found == NULL)
1173         {
1174                 g_free (line_text);
1175                 return FALSE;
1176         }
1177
1178         /* Get offset to start of search string */
1179         offset = g_utf8_strlen (line_text, found - line_text);
1180
1181         next = *start;
1182
1183         /* If match start needs to be returned, set it to the
1184          * start of the search string.
1185          */
1186         forward_chars_with_skipping (&next, offset, visible_only, !slice, FALSE);
1187         if (match_start)
1188         {
1189                 *match_start = next;
1190         }
1191
1192         /* Go to end of search string */
1193         forward_chars_with_skipping (&next, g_utf8_strlen (*lines, -1), visible_only, !slice, TRUE);
1194
1195         g_free (line_text);
1196
1197         ++lines;
1198
1199         if (match_end)
1200                 *match_end = next;
1201
1202         /* pass NULL for match_start, since we don't need to find the
1203          * start again.
1204          */
1205         return lines_match (&next, lines, visible_only, slice, NULL, match_end);
1206 }
1207
1208 /* strsplit () that retains the delimiter as part of the string. */
1209 static gchar **
1210 strbreakup (const char *string,
1211             const char *delimiter,
1212             gint        max_tokens)
1213 {
1214         GSList *string_list = NULL, *slist;
1215         gchar **str_array, *s, *casefold, *new_string;
1216         guint i, n = 1;
1217
1218         g_return_val_if_fail (string != NULL, NULL);
1219         g_return_val_if_fail (delimiter != NULL, NULL);
1220
1221         if (max_tokens < 1)
1222                 max_tokens = G_MAXINT;
1223
1224         s = strstr (string, delimiter);
1225         if (s)
1226         {
1227                 guint delimiter_len = strlen (delimiter);
1228
1229                 do
1230                 {
1231                         guint len;
1232
1233                         len = s - string + delimiter_len;
1234                         new_string = g_new (gchar, len + 1);
1235                         strncpy (new_string, string, len);
1236                         new_string[len] = 0;
1237                         casefold = g_utf8_casefold (new_string, -1);
1238                         g_free (new_string);
1239                         new_string = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1240                         g_free (casefold);
1241                         string_list = g_slist_prepend (string_list, new_string);
1242                         n++;
1243                         string = s + delimiter_len;
1244                         s = strstr (string, delimiter);
1245                 } while (--max_tokens && s);
1246         }
1247
1248         if (*string)
1249         {
1250                 n++;
1251                 casefold = g_utf8_casefold (string, -1);
1252                 new_string = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1253                 g_free (casefold);
1254                 string_list = g_slist_prepend (string_list, new_string);
1255         }
1256
1257         str_array = g_new (gchar*, n);
1258
1259         i = n - 1;
1260
1261         str_array[i--] = NULL;
1262         for (slist = string_list; slist; slist = slist->next)
1263                 str_array[i--] = slist->data;
1264
1265         g_slist_free (string_list);
1266
1267         return str_array;
1268 }
1269
1270 gboolean
1271 empathy_text_iter_forward_search (const GtkTextIter   *iter,
1272                                  const gchar         *str,
1273                                  GtkTextIter         *match_start,
1274                                  GtkTextIter         *match_end,
1275                                  const GtkTextIter   *limit)
1276 {
1277         gchar **lines = NULL;
1278         GtkTextIter match;
1279         gboolean retval = FALSE;
1280         GtkTextIter search;
1281         gboolean visible_only;
1282         gboolean slice;
1283
1284         g_return_val_if_fail (iter != NULL, FALSE);
1285         g_return_val_if_fail (str != NULL, FALSE);
1286
1287         if (limit && gtk_text_iter_compare (iter, limit) >= 0)
1288                 return FALSE;
1289
1290         if (*str == '\0') {
1291                 /* If we can move one char, return the empty string there */
1292                 match = *iter;
1293
1294                 if (gtk_text_iter_forward_char (&match)) {
1295                         if (limit && gtk_text_iter_equal (&match, limit)) {
1296                                 return FALSE;
1297                         }
1298
1299                         if (match_start) {
1300                                 *match_start = match;
1301                         }
1302                         if (match_end) {
1303                                 *match_end = match;
1304                         }
1305                         return TRUE;
1306                 } else {
1307                         return FALSE;
1308                 }
1309         }
1310
1311         visible_only = TRUE;
1312         slice = FALSE;
1313
1314         /* locate all lines */
1315         lines = strbreakup (str, "\n", -1);
1316
1317         search = *iter;
1318
1319         do {
1320                 /* This loop has an inefficient worst-case, where
1321                  * gtk_text_iter_get_text () is called repeatedly on
1322                  * a single line.
1323                  */
1324                 GtkTextIter end;
1325
1326                 if (limit && gtk_text_iter_compare (&search, limit) >= 0) {
1327                         break;
1328                 }
1329
1330                 if (lines_match (&search, (const gchar**)lines,
1331                                  visible_only, slice, &match, &end)) {
1332                         if (limit == NULL ||
1333                             (limit && gtk_text_iter_compare (&end, limit) <= 0)) {
1334                                 retval = TRUE;
1335
1336                                 if (match_start) {
1337                                         *match_start = match;
1338                                 }
1339                                 if (match_end) {
1340                                         *match_end = end;
1341                                 }
1342                         }
1343                         break;
1344                 }
1345         } while (gtk_text_iter_forward_line (&search));
1346
1347         g_strfreev ((gchar **) lines);
1348
1349         return retval;
1350 }
1351
1352 static const gchar *
1353 g_utf8_strrcasestr (const gchar *haystack, const gchar *needle)
1354 {
1355         gsize needle_len;
1356         gsize haystack_len;
1357         const gchar *ret = NULL;
1358         gchar *p;
1359         gchar *casefold;
1360         gchar *caseless_haystack;
1361         gint i;
1362
1363         g_return_val_if_fail (haystack != NULL, NULL);
1364         g_return_val_if_fail (needle != NULL, NULL);
1365
1366         casefold = g_utf8_casefold (haystack, -1);
1367         caseless_haystack = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1368         g_free (casefold);
1369
1370         needle_len = g_utf8_strlen (needle, -1);
1371         haystack_len = g_utf8_strlen (caseless_haystack, -1);
1372
1373         if (needle_len == 0)
1374         {
1375                 ret = (gchar *) haystack;
1376                 goto finally_1;
1377         }
1378
1379         if (haystack_len < needle_len)
1380         {
1381                 ret = NULL;
1382                 goto finally_1;
1383         }
1384
1385         i = haystack_len - needle_len;
1386         p = g_utf8_offset_to_pointer (caseless_haystack, i);
1387         needle_len = strlen (needle);
1388
1389         while (p >= caseless_haystack)
1390         {
1391                 if (strncmp (p, needle, needle_len) == 0)
1392                 {
1393                         ret = pointer_from_offset_skipping_decomp (haystack, i);
1394                         goto finally_1;
1395                 }
1396
1397                 p = g_utf8_prev_char (p);
1398                 i--;
1399         }
1400
1401 finally_1:
1402         g_free (caseless_haystack);
1403
1404         return ret;
1405 }
1406
1407 static gboolean
1408 backward_lines_match (const GtkTextIter *start,
1409                       const gchar      **lines,
1410                       gboolean           visible_only,
1411                       gboolean           slice,
1412                       GtkTextIter       *match_start,
1413                       GtkTextIter       *match_end)
1414 {
1415         GtkTextIter line, next;
1416         gchar *line_text;
1417         const gchar *found;
1418         gint offset;
1419
1420         if (*lines == NULL || **lines == '\0')
1421         {
1422                 if (match_start)
1423                         *match_start = *start;
1424                 if (match_end)
1425                         *match_end = *start;
1426                 return TRUE;
1427         }
1428
1429         line = next = *start;
1430         if (gtk_text_iter_get_line_offset (&next) == 0)
1431         {
1432                 if (!gtk_text_iter_backward_line (&next))
1433                         return FALSE;
1434         }
1435         else
1436                 gtk_text_iter_set_line_offset (&next, 0);
1437
1438         if (slice)
1439         {
1440                 if (visible_only)
1441                         line_text = gtk_text_iter_get_visible_slice (&next, &line);
1442                 else
1443                         line_text = gtk_text_iter_get_slice (&next, &line);
1444         }
1445         else
1446         {
1447                 if (visible_only)
1448                         line_text = gtk_text_iter_get_visible_text (&next, &line);
1449                 else
1450                         line_text = gtk_text_iter_get_text (&next, &line);
1451         }
1452
1453         if (match_start) /* if this is the first line we're matching */
1454         {
1455                 found = g_utf8_strrcasestr (line_text, *lines);
1456         }
1457         else
1458         {
1459                 /* If it's not the first line, we have to match from the
1460                  * start of the line.
1461                  */
1462                 if (g_utf8_caselessnmatch (line_text, *lines, strlen (line_text),
1463                                            strlen (*lines)))
1464                         found = line_text;
1465                 else
1466                         found = NULL;
1467         }
1468
1469         if (found == NULL)
1470         {
1471                 g_free (line_text);
1472                 return FALSE;
1473         }
1474
1475         /* Get offset to start of search string */
1476         offset = g_utf8_strlen (line_text, found - line_text);
1477
1478         forward_chars_with_skipping (&next, offset, visible_only, !slice, FALSE);
1479
1480         /* If match start needs to be returned, set it to the
1481          * start of the search string.
1482          */
1483         if (match_start)
1484         {
1485                 *match_start = next;
1486         }
1487
1488         /* Go to end of search string */
1489         forward_chars_with_skipping (&next, g_utf8_strlen (*lines, -1), visible_only, !slice, TRUE);
1490
1491         g_free (line_text);
1492
1493         ++lines;
1494
1495         if (match_end)
1496                 *match_end = next;
1497
1498         /* try to match the rest of the lines forward, passing NULL
1499          * for match_start so lines_match will try to match the entire
1500          * line */
1501         return lines_match (&next, lines, visible_only,
1502                             slice, NULL, match_end);
1503 }
1504
1505 gboolean
1506 empathy_text_iter_backward_search (const GtkTextIter   *iter,
1507                                   const gchar         *str,
1508                                   GtkTextIter         *match_start,
1509                                   GtkTextIter         *match_end,
1510                                   const GtkTextIter   *limit)
1511 {
1512         gchar **lines = NULL;
1513         GtkTextIter match;
1514         gboolean retval = FALSE;
1515         GtkTextIter search;
1516         gboolean visible_only;
1517         gboolean slice;
1518
1519         g_return_val_if_fail (iter != NULL, FALSE);
1520         g_return_val_if_fail (str != NULL, FALSE);
1521
1522         if (limit && gtk_text_iter_compare (iter, limit) <= 0)
1523                 return FALSE;
1524
1525         if (*str == '\0')
1526         {
1527                 /* If we can move one char, return the empty string there */
1528                 match = *iter;
1529
1530                 if (gtk_text_iter_backward_char (&match))
1531                 {
1532                         if (limit && gtk_text_iter_equal (&match, limit))
1533                                 return FALSE;
1534
1535                         if (match_start)
1536                                 *match_start = match;
1537                         if (match_end)
1538                                 *match_end = match;
1539                         return TRUE;
1540                 }
1541                 else
1542                 {
1543                         return FALSE;
1544                 }
1545         }
1546
1547         visible_only = TRUE;
1548         slice = TRUE;
1549
1550         /* locate all lines */
1551         lines = strbreakup (str, "\n", -1);
1552
1553         search = *iter;
1554
1555         while (TRUE)
1556         {
1557                 /* This loop has an inefficient worst-case, where
1558                  * gtk_text_iter_get_text () is called repeatedly on
1559                  * a single line.
1560                  */
1561                 GtkTextIter end;
1562
1563                 if (limit && gtk_text_iter_compare (&search, limit) <= 0)
1564                         break;
1565
1566                 if (backward_lines_match (&search, (const gchar**)lines,
1567                                           visible_only, slice, &match, &end))
1568                 {
1569                         if (limit == NULL || (limit &&
1570                                               gtk_text_iter_compare (&end, limit) > 0))
1571                         {
1572                                 retval = TRUE;
1573
1574                                 if (match_start)
1575                                         *match_start = match;
1576                                 if (match_end)
1577                                         *match_end = end;
1578                         }
1579                         break;
1580                 }
1581
1582                 if (gtk_text_iter_get_line_offset (&search) == 0)
1583                 {
1584                         if (!gtk_text_iter_backward_line (&search))
1585                                 break;
1586                 }
1587                 else
1588                 {
1589                         gtk_text_iter_set_line_offset (&search, 0);
1590                 }
1591         }
1592
1593         g_strfreev ((gchar **) lines);
1594
1595         return retval;
1596 }
1597
1598 /* Takes care of moving the window to the current workspace. */
1599 void
1600 empathy_window_present_with_time (GtkWindow *window,
1601                         guint32 timestamp)
1602 {
1603         GdkWindow *gdk_window;
1604
1605         g_return_if_fail (GTK_IS_WINDOW (window));
1606
1607         /* Move the window to the current workspace before trying to show it.
1608          * This is the behaviour people expect when clicking on the statusbar icon. */
1609         gdk_window = gtk_widget_get_window (GTK_WIDGET (window));
1610         if (gdk_window) {
1611                 gint x, y;
1612                 gint w, h;
1613
1614                 /* Has no effect if the WM has viewports, like compiz */
1615                 gdk_x11_window_move_to_current_desktop (gdk_window);
1616
1617                 /* If window is still off-screen, hide it to force it to
1618                  * reposition on the current workspace. */
1619                 gtk_window_get_position (window, &x, &y);
1620                 gtk_window_get_size (window, &w, &h);
1621                 if (!EMPATHY_RECT_IS_ON_SCREEN (x, y, w, h))
1622                         gtk_widget_hide (GTK_WIDGET (window));
1623         }
1624
1625         if (timestamp == GDK_CURRENT_TIME)
1626                 gtk_window_present (window);
1627         else
1628                 gtk_window_present_with_time (window, timestamp);
1629 }
1630
1631 void
1632 empathy_window_present (GtkWindow *window)
1633 {
1634   empathy_window_present_with_time (window, gtk_get_current_event_time ());
1635 }
1636
1637 GtkWindow *
1638 empathy_get_toplevel_window (GtkWidget *widget)
1639 {
1640         GtkWidget *toplevel;
1641
1642         g_return_val_if_fail (GTK_IS_WIDGET (widget), NULL);
1643
1644         toplevel = gtk_widget_get_toplevel (widget);
1645         if (GTK_IS_WINDOW (toplevel) &&
1646             gtk_widget_is_toplevel (toplevel)) {
1647                 return GTK_WINDOW (toplevel);
1648         }
1649
1650         return NULL;
1651 }
1652
1653 /** empathy_make_absolute_url_len:
1654  * @url: an url
1655  * @len: a length
1656  *
1657  * Same as #empathy_make_absolute_url but for a limited string length
1658  */
1659 gchar *
1660 empathy_make_absolute_url_len (const gchar *url,
1661                                guint len)
1662 {
1663         g_return_val_if_fail (url != NULL, NULL);
1664
1665         if (g_str_has_prefix (url, "ghelp:") ||
1666             g_str_has_prefix (url, "mailto:") ||
1667             strstr (url, ":/")) {
1668                 return g_strndup (url, len);
1669         }
1670
1671         if (strstr (url, "@")) {
1672                 return g_strdup_printf ("mailto:%.*s", len, url);
1673         }
1674
1675         return g_strdup_printf ("http://%.*s", len, url);
1676 }
1677
1678 /** empathy_make_absolute_url:
1679  * @url: an url
1680  *
1681  * The URL opening code can't handle schemeless strings, so we try to be
1682  * smart and add http if there is no scheme or doesn't look like a mail
1683  * address. This should work in most cases, and let us click on strings
1684  * like "www.gnome.org".
1685  *
1686  * Returns: a newly allocated url with proper mailto: or http:// prefix, use
1687  * g_free when your are done with it
1688  */
1689 gchar *
1690 empathy_make_absolute_url (const gchar *url)
1691 {
1692         return empathy_make_absolute_url_len (url, strlen (url));
1693 }
1694
1695 void
1696 empathy_url_show (GtkWidget *parent,
1697                   const char *url)
1698 {
1699         gchar  *real_url;
1700         GError *error = NULL;
1701
1702         g_return_if_fail (parent == NULL || GTK_IS_WIDGET (parent));
1703         g_return_if_fail (url != NULL);
1704
1705         real_url = empathy_make_absolute_url (url);
1706
1707         gtk_show_uri (parent ? gtk_widget_get_screen (parent) : NULL, real_url,
1708                       gtk_get_current_event_time (), &error);
1709
1710         if (error) {
1711                 GtkWidget *dialog;
1712
1713                 dialog = gtk_message_dialog_new (NULL, 0,
1714                                                  GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,
1715                                                  _("Unable to open URI"));
1716                 gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
1717                                                           "%s", error->message);
1718
1719                 g_signal_connect (dialog, "response",
1720                                   G_CALLBACK (gtk_widget_destroy),
1721                                   NULL);
1722                 gtk_window_present (GTK_WINDOW (dialog));
1723
1724                 g_clear_error (&error);
1725         }
1726
1727         g_free (real_url);
1728 }
1729
1730 void
1731 empathy_send_file (EmpathyContact *contact, GFile *file)
1732 {
1733         EmpathyFTFactory *factory;
1734         GtkRecentManager *manager;
1735         gchar *uri;
1736
1737         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1738         g_return_if_fail (G_IS_FILE (file));
1739
1740         factory = empathy_ft_factory_dup_singleton ();
1741
1742         empathy_ft_factory_new_transfer_outgoing (factory, contact, file);
1743
1744         uri = g_file_get_uri (file);
1745         manager = gtk_recent_manager_get_default ();
1746         gtk_recent_manager_add_item (manager, uri);
1747         g_free (uri);
1748
1749         g_object_unref (factory);
1750 }
1751
1752 void
1753 empathy_send_file_from_uri_list (EmpathyContact *contact, const gchar *uri_list)
1754 {
1755         const gchar *nl;
1756         GFile *file;
1757
1758         /* Only handle a single file for now.  It would be wicked cool to be
1759            able to do multiple files, offering to zip them or whatever like
1760            nautilus-sendto does.  Note that text/uri-list is defined to have
1761            each line terminated by \r\n, but we can be tolerant of applications
1762            that only use \n or don't terminate single-line entries.
1763         */
1764         nl = strstr (uri_list, "\r\n");
1765         if (!nl) {
1766                 nl = strchr (uri_list, '\n');
1767         }
1768         if (nl) {
1769                 gchar *uri = g_strndup (uri_list, nl - uri_list);
1770                 file = g_file_new_for_uri (uri);
1771                 g_free (uri);
1772         }
1773         else {
1774                 file = g_file_new_for_uri (uri_list);
1775         }
1776
1777         empathy_send_file (contact, file);
1778
1779         g_object_unref (file);
1780 }
1781
1782 static void
1783 file_manager_send_file_response_cb (GtkDialog      *widget,
1784                                     gint            response_id,
1785                                     EmpathyContact *contact)
1786 {
1787         GFile *file;
1788
1789         if (response_id == GTK_RESPONSE_OK) {
1790                 file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (widget));
1791
1792                 empathy_send_file (contact, file);
1793
1794                 g_object_unref (file);
1795         }
1796
1797         g_object_unref (contact);
1798         gtk_widget_destroy (GTK_WIDGET (widget));
1799 }
1800
1801 void
1802 empathy_send_file_with_file_chooser (EmpathyContact *contact)
1803 {
1804         GtkWidget               *widget;
1805         GtkWidget               *button;
1806
1807         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1808
1809         DEBUG ("Creating selection file chooser");
1810
1811         widget = gtk_file_chooser_dialog_new (_("Select a file"),
1812                                               NULL,
1813                                               GTK_FILE_CHOOSER_ACTION_OPEN,
1814                                               GTK_STOCK_CANCEL,
1815                                               GTK_RESPONSE_CANCEL,
1816                                               NULL);
1817
1818         /* send button */
1819         button = gtk_button_new_with_mnemonic (_("_Send"));
1820         gtk_button_set_image (GTK_BUTTON (button),
1821                 gtk_image_new_from_icon_name (EMPATHY_IMAGE_DOCUMENT_SEND,
1822                                               GTK_ICON_SIZE_BUTTON));
1823         gtk_widget_show (button);
1824         gtk_dialog_add_action_widget (GTK_DIALOG (widget), button,
1825                                       GTK_RESPONSE_OK);
1826         gtk_widget_set_can_default (button, TRUE);
1827         gtk_dialog_set_default_response (GTK_DIALOG (widget),
1828                                          GTK_RESPONSE_OK);
1829
1830         gtk_file_chooser_set_local_only (GTK_FILE_CHOOSER (widget), FALSE);
1831
1832         gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (widget),
1833                 g_get_home_dir ());
1834
1835         g_signal_connect (widget, "response",
1836                           G_CALLBACK (file_manager_send_file_response_cb),
1837                           g_object_ref (contact));
1838
1839         gtk_widget_show (widget);
1840 }
1841
1842 static void
1843 file_manager_receive_file_response_cb (GtkDialog *dialog,
1844                                        GtkResponseType response,
1845                                        EmpathyFTHandler *handler)
1846 {
1847         EmpathyFTFactory *factory;
1848         GFile *file;
1849
1850         if (response == GTK_RESPONSE_OK) {
1851                 GFile *parent;
1852                 GFileInfo *info;
1853                 guint64 free_space, file_size;
1854                 GError *error = NULL;
1855
1856                 file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (dialog));
1857                 parent = g_file_get_parent (file);
1858                 info = g_file_query_filesystem_info (parent,
1859                                 G_FILE_ATTRIBUTE_FILESYSTEM_FREE,
1860                                 NULL, &error);
1861
1862                 g_object_unref (parent);
1863
1864                 if (error != NULL) {
1865                         g_warning ("Error: %s", error->message);
1866
1867                         g_object_unref (file);
1868                         return;
1869                 }
1870
1871                 free_space = g_file_info_get_attribute_uint64 (info,
1872                                 G_FILE_ATTRIBUTE_FILESYSTEM_FREE);
1873                 file_size = empathy_ft_handler_get_total_bytes (handler);
1874
1875                 g_object_unref (info);
1876
1877                 if (file_size > free_space) {
1878                         GtkWidget *message = gtk_message_dialog_new (
1879                                 GTK_WINDOW (dialog),
1880                                 GTK_DIALOG_MODAL,
1881                                 GTK_MESSAGE_ERROR,
1882                                 GTK_BUTTONS_CLOSE,
1883                                 _("Insufficient free space to save file"));
1884                         char *file_size_str, *free_space_str;
1885
1886                         file_size_str = g_format_size_for_display (file_size);
1887                         free_space_str = g_format_size_for_display (free_space);
1888
1889                         gtk_message_dialog_format_secondary_text (
1890                                 GTK_MESSAGE_DIALOG (message),
1891                                 _("%s of free space are required to save this "
1892                                   "file, but only %s is available. Please "
1893                                   "choose another location."),
1894                                 file_size_str, free_space_str);
1895
1896                         gtk_dialog_run (GTK_DIALOG (message));
1897
1898                         g_free (file_size_str);
1899                         g_free (free_space_str);
1900                         gtk_widget_destroy (message);
1901
1902                         g_object_unref (file);
1903
1904                         return;
1905                 }
1906
1907                 factory = empathy_ft_factory_dup_singleton ();
1908
1909                 empathy_ft_factory_set_destination_for_incoming_handler (
1910                                 factory, handler, file);
1911
1912                 g_object_unref (factory);
1913                 g_object_unref (file);
1914         } else {
1915                 /* unref the handler, as we dismissed the file chooser,
1916                  * and refused the transfer.
1917                  */
1918                 g_object_unref (handler);
1919         }
1920
1921         gtk_widget_destroy (GTK_WIDGET (dialog));
1922 }
1923
1924 void
1925 empathy_receive_file_with_file_chooser (EmpathyFTHandler *handler)
1926 {
1927         GtkWidget *widget;
1928         const gchar *dir;
1929         EmpathyContact *contact;
1930         gchar *title;
1931
1932         contact = empathy_ft_handler_get_contact (handler);
1933         g_assert (contact != NULL);
1934
1935         title = g_strdup_printf (_("Incoming file from %s"),
1936                 empathy_contact_get_alias (contact));
1937
1938         widget = gtk_file_chooser_dialog_new (title,
1939                                               NULL,
1940                                               GTK_FILE_CHOOSER_ACTION_SAVE,
1941                                               GTK_STOCK_CANCEL,
1942                                               GTK_RESPONSE_CANCEL,
1943                                               GTK_STOCK_SAVE,
1944                                               GTK_RESPONSE_OK,
1945                                               NULL);
1946         gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (widget),
1947                 empathy_ft_handler_get_filename (handler));
1948         gtk_file_chooser_set_do_overwrite_confirmation
1949                 (GTK_FILE_CHOOSER (widget), TRUE);
1950
1951         dir = g_get_user_special_dir (G_USER_DIRECTORY_DOWNLOAD);
1952         if (dir == NULL)
1953                 /* Fallback to $HOME if $XDG_DOWNLOAD_DIR is not set */
1954                 dir = g_get_home_dir ();
1955
1956         gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (widget), dir);
1957
1958         g_signal_connect (widget, "response",
1959                 G_CALLBACK (file_manager_receive_file_response_cb), handler);
1960
1961         gtk_widget_show (widget);
1962         g_free (title);
1963 }
1964
1965 void
1966 empathy_make_color_whiter (GdkRGBA *color)
1967 {
1968         const GdkRGBA white = { 1.0, 1.0, 1.0, 1.0 };
1969
1970         color->red = (color->red + white.red) / 2;
1971         color->green = (color->green + white.green) / 2;
1972         color->blue = (color->blue + white.blue) / 2;
1973 }
1974
1975 static void
1976 menu_deactivate_cb (GtkMenu *menu,
1977         gpointer user_data)
1978 {
1979         /* FIXME: we shouldn't have to disconnect the signal (bgo #641327) */
1980         g_signal_handlers_disconnect_by_func (menu,
1981                      menu_deactivate_cb, user_data);
1982
1983         gtk_menu_detach (menu);
1984 }
1985
1986 /* Convenient function to create a GtkMenu attached to @attach_to and detach
1987  * it when the menu is not displayed any more. This is useful when creating a
1988  * context menu that we want to get rid as soon as it as been displayed. */
1989 GtkWidget *
1990 empathy_context_menu_new (GtkWidget *attach_to)
1991 {
1992         GtkWidget *menu;
1993
1994         menu = gtk_menu_new ();
1995
1996         gtk_menu_attach_to_widget (GTK_MENU (menu), attach_to, NULL);
1997
1998         /* menu is initially unowned but gtk_menu_attach_to_widget () taked its
1999          * floating ref. We can either wait that @attach_to releases its ref when
2000          * it will be destroyed (when leaving Empathy most of the time) or explicitely
2001          * detach the menu when it's not displayed any more.
2002          * We go for the latter as we don't want to keep useless menus in memory
2003          * during the whole lifetime of Empathy. */
2004         g_signal_connect (menu, "deactivate", G_CALLBACK (menu_deactivate_cb), NULL);
2005
2006         return menu;
2007 }
2008
2009 gint64
2010 empathy_get_current_action_time (void)
2011 {
2012   return (tp_user_action_time_from_x11 (gtk_get_current_event_time ()));
2013 }
2014
2015 /* @words = empathy_live_search_strip_utf8_string (@text);
2016  *
2017  * User has to pass both so we don't have to compute @words ourself each time
2018  * this function is called. */
2019 gboolean
2020 empathy_individual_match_string (FolksIndividual *individual,
2021     const char *text,
2022     GPtrArray *words)
2023 {
2024   const gchar *str;
2025   GeeSet *personas;
2026   GeeIterator *iter;
2027   gboolean retval = FALSE;
2028
2029   /* check alias name */
2030   str = folks_alias_details_get_alias (FOLKS_ALIAS_DETAILS (individual));
2031
2032   if (empathy_live_search_match_words (str, words))
2033     return TRUE;
2034
2035   personas = folks_individual_get_personas (individual);
2036
2037   /* check contact id, remove the @server.com part */
2038   iter = gee_iterable_iterator (GEE_ITERABLE (personas));
2039   while (retval == FALSE && gee_iterator_next (iter))
2040     {
2041       FolksPersona *persona = gee_iterator_get (iter);
2042       const gchar *p;
2043
2044       if (empathy_folks_persona_is_interesting (persona))
2045         {
2046           str = folks_persona_get_display_id (persona);
2047
2048           /* Accept the persona if @text is a full prefix of his ID; that allows
2049            * user to find, say, a jabber contact by typing his JID. */
2050           if (g_str_has_prefix (str, text))
2051             {
2052               retval = TRUE;
2053             }
2054           else
2055             {
2056               gchar *dup_str = NULL;
2057               gboolean visible;
2058
2059               p = strstr (str, "@");
2060               if (p != NULL)
2061                 str = dup_str = g_strndup (str, p - str);
2062
2063               visible = empathy_live_search_match_words (str, words);
2064               g_free (dup_str);
2065               if (visible)
2066                 retval = TRUE;
2067             }
2068         }
2069       g_clear_object (&persona);
2070     }
2071   g_clear_object (&iter);
2072
2073   /* FIXME: Add more rules here, we could check phone numbers in
2074    * contact's vCard for example. */
2075   return retval;
2076 }
2077
2078 static gboolean
2079 dtmf_dialpad_button_pressed_cb (GObject *button,
2080     GtkEntry *entry)
2081 {
2082   GtkEntryBuffer *buffer = gtk_entry_get_buffer (entry);
2083   const gchar *label;
2084
2085   label = g_object_get_data (button, "label");
2086   gtk_entry_buffer_insert_text (buffer, -1, label, -1);
2087
2088   return FALSE;
2089 }
2090
2091 GtkWidget *
2092 empathy_create_dtmf_dialpad (GObject *self,
2093     GCallback dtmf_button_pressed_cb,
2094     GCallback dtmf_button_released_cb)
2095 {
2096   GtkWidget *box, *entry, *table;
2097   int i;
2098   GQuark button_quark;
2099   struct {
2100     const gchar *label;
2101     const gchar *sublabel;
2102     TpDTMFEvent event;
2103   } dtmfbuttons[] = { { "1", "",     TP_DTMF_EVENT_DIGIT_1 },
2104                       { "2", "abc",  TP_DTMF_EVENT_DIGIT_2 },
2105                       { "3", "def",  TP_DTMF_EVENT_DIGIT_3 },
2106                       { "4", "ghi",  TP_DTMF_EVENT_DIGIT_4 },
2107                       { "5", "jkl",  TP_DTMF_EVENT_DIGIT_5 },
2108                       { "6", "mno",  TP_DTMF_EVENT_DIGIT_6 },
2109                       { "7", "pqrs", TP_DTMF_EVENT_DIGIT_7 },
2110                       { "8", "tuv",  TP_DTMF_EVENT_DIGIT_8 },
2111                       { "9", "wxyz", TP_DTMF_EVENT_DIGIT_9 },
2112                       { "#", "",     TP_DTMF_EVENT_HASH },
2113                       { "0", "",     TP_DTMF_EVENT_DIGIT_0 },
2114                       { "*", "",     TP_DTMF_EVENT_ASTERISK },
2115                       { NULL, } };
2116
2117   box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 3);
2118
2119   entry = gtk_entry_new ();
2120   gtk_editable_set_editable (GTK_EDITABLE (entry), FALSE);
2121
2122   gtk_box_pack_start (GTK_BOX (box), entry, FALSE, FALSE, 3);
2123
2124   button_quark = g_quark_from_static_string (EMPATHY_DTMF_BUTTON_ID);
2125
2126   table = gtk_table_new (4, 3, TRUE);
2127
2128   for (i = 0; dtmfbuttons[i].label != NULL; i++)
2129     {
2130       GtkWidget *vbox = gtk_vbox_new (FALSE, 0);
2131       GtkWidget *button = gtk_button_new ();
2132       GtkWidget *label;
2133       gchar *str;
2134
2135       gtk_container_add (GTK_CONTAINER (button), vbox);
2136
2137       /* main label */
2138       label = gtk_label_new ("");
2139       str = g_strdup_printf ("<span size='x-large'>%s</span>",
2140           dtmfbuttons[i].label);
2141       gtk_label_set_markup (GTK_LABEL (label), str);
2142       g_free (str);
2143
2144       g_object_set_data (G_OBJECT (button), "label",
2145           (gpointer) dtmfbuttons[i].label);
2146
2147       gtk_box_pack_start (GTK_BOX (vbox), label, TRUE, TRUE, 3);
2148
2149       /* sub label */
2150       label = gtk_label_new ("");
2151       str = g_strdup_printf (
2152           "<span foreground='#555555'>%s</span>",
2153           dtmfbuttons[i].sublabel);
2154       gtk_label_set_markup (GTK_LABEL (label), str);
2155       g_free (str);
2156
2157       gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, TRUE, 0);
2158
2159       gtk_table_attach (GTK_TABLE (table), button, i % 3, i % 3 + 1,
2160         i/3, i/3 + 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 1, 1);
2161
2162       g_object_set_qdata (G_OBJECT (button), button_quark,
2163         GUINT_TO_POINTER (dtmfbuttons[i].event));
2164
2165       /* To update the GtkEntry */
2166       g_signal_connect (G_OBJECT (button), "pressed",
2167         G_CALLBACK (dtmf_dialpad_button_pressed_cb), entry);
2168
2169       g_signal_connect (G_OBJECT (button), "pressed",
2170         dtmf_button_pressed_cb, self);
2171       g_signal_connect (G_OBJECT (button), "released",
2172         dtmf_button_released_cb, self);
2173     }
2174
2175   gtk_box_pack_start (GTK_BOX (box), table, FALSE, FALSE, 3);
2176
2177   return box;
2178 }
2179
2180 void
2181 empathy_launch_program (const gchar *dir,
2182     const gchar *name,
2183     const gchar *args)
2184 {
2185   GdkDisplay *display;
2186   GError *error = NULL;
2187   gchar *path, *cmd;
2188   GAppInfo *app_info;
2189   GdkAppLaunchContext *context = NULL;
2190
2191   /* Try to run from source directory if possible */
2192   path = g_build_filename (g_getenv ("EMPATHY_SRCDIR"), "src",
2193       name, NULL);
2194
2195   if (!g_file_test (path, G_FILE_TEST_EXISTS))
2196     {
2197       g_free (path);
2198       path = g_build_filename (dir, name, NULL);
2199     }
2200
2201   if (args != NULL)
2202     cmd = g_strconcat (path, " ", args, NULL);
2203   else
2204     cmd = g_strdup (path);
2205
2206   app_info = g_app_info_create_from_commandline (cmd, NULL, 0, &error);
2207   if (app_info == NULL)
2208     {
2209       DEBUG ("Failed to create app info: %s", error->message);
2210       g_error_free (error);
2211       goto out;
2212     }
2213
2214   display = gdk_display_get_default ();
2215   context = gdk_display_get_app_launch_context (display);
2216
2217   if (!g_app_info_launch (app_info, NULL, (GAppLaunchContext *) context,
2218       &error))
2219     {
2220       g_warning ("Failed to launch %s: %s", name, error->message);
2221       g_error_free (error);
2222       goto out;
2223     }
2224
2225 out:
2226   tp_clear_object (&app_info);
2227   tp_clear_object (&context);
2228   g_free (path);
2229   g_free (cmd);
2230 }