]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-ui-utils.c
Merge branch: 'Add top-up link to chat text when there is insufficient credit'
[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_close_cb (GObject      *object,
570                            GAsyncResult *result,
571                            gpointer      user_data)
572 {
573         GError *error = NULL;
574
575         g_input_stream_close_finish (G_INPUT_STREAM (object), result, &error);
576
577         if (error != NULL) {
578                 DEBUG ("Failed to close pixbuf stream: %s", error->message);
579                 g_error_free (error);
580         }
581 }
582
583 static void
584 avatar_icon_load_read_cb (GObject      *object,
585                           GAsyncResult *result,
586                           gpointer      user_data)
587 {
588         GInputStream *stream = G_INPUT_STREAM (object);
589         PixbufAvatarFromIndividualClosure *closure = user_data;
590         gssize n_read;
591         GError *error = NULL;
592
593         /* Finish reading this chunk from the stream */
594         n_read = g_input_stream_read_finish (stream, result, &error);
595         if (error != NULL) {
596                 DEBUG ("Failed to finish read from pixbuf stream: %s",
597                         error->message);
598                 g_simple_async_result_set_from_error (closure->result, error);
599                 goto out_close;
600         }
601
602         /* Write the chunk to the pixbuf loader */
603         if (!gdk_pixbuf_loader_write (closure->loader, (guchar *) closure->data,
604                         n_read, &error)) {
605                 DEBUG ("Failed to write to pixbuf loader: %s",
606                         error ? error->message : "No error given");
607                 g_simple_async_result_set_from_error (closure->result, error);
608                 goto out_close;
609         }
610
611         if (n_read == 0) {
612                 /* EOF? */
613                 if (!gdk_pixbuf_loader_close (closure->loader, &error)) {
614                         DEBUG ("Failed to close pixbuf loader: %s",
615                                 error ? error->message : "No error given");
616                         g_simple_async_result_set_from_error (closure->result, error);
617                         goto out;
618                 }
619
620                 /* We're done. */
621                 g_simple_async_result_set_op_res_gpointer (closure->result,
622                         avatar_pixbuf_from_loader (closure->loader),
623                         g_object_unref);
624
625                 goto out;
626         } else {
627                 /* Loop round and read another chunk. */
628                 g_input_stream_read_async (stream, closure->data,
629                         G_N_ELEMENTS (closure->data),
630                         G_PRIORITY_DEFAULT, closure->cancellable,
631                         avatar_icon_load_read_cb, closure);
632
633                 return;
634         }
635
636 out_close:
637         /* We must close the pixbuf loader before unreffing it. */
638         gdk_pixbuf_loader_close (closure->loader, NULL);
639
640 out:
641         /* Close the file for safety (even though it should be
642          * automatically closed when the stream is finalised). */
643         g_input_stream_close_async (stream, G_PRIORITY_DEFAULT, NULL,
644                 (GAsyncReadyCallback) avatar_icon_load_close_cb, NULL);
645
646         g_simple_async_result_complete (closure->result);
647
648         g_clear_error (&error);
649         pixbuf_avatar_from_individual_closure_free (closure);
650 }
651
652 static void
653 avatar_icon_load_cb (GObject      *object,
654                      GAsyncResult *result,
655                      gpointer      user_data)
656 {
657         GLoadableIcon *icon = G_LOADABLE_ICON (object);
658         PixbufAvatarFromIndividualClosure *closure = user_data;
659         GInputStream *stream;
660         GError *error = NULL;
661
662         stream = g_loadable_icon_load_finish (icon, result, NULL, &error);
663         if (error != NULL) {
664                 DEBUG ("Failed to open avatar stream: %s", error->message);
665                 g_simple_async_result_set_from_error (closure->result, error);
666                 goto out;
667         }
668
669         closure->size_data.width = closure->width;
670         closure->size_data.height = closure->height;
671         closure->size_data.preserve_aspect_ratio = TRUE;
672
673         /* Load the data into a pixbuf loader in chunks. */
674         closure->loader = gdk_pixbuf_loader_new ();
675
676         g_signal_connect (closure->loader, "size-prepared",
677                           G_CALLBACK (pixbuf_from_avatar_size_prepared_cb),
678                           &(closure->size_data));
679
680         /* Begin to read the first chunk. */
681         g_input_stream_read_async (stream, closure->data,
682                         G_N_ELEMENTS (closure->data),
683                         G_PRIORITY_DEFAULT, closure->cancellable,
684                         avatar_icon_load_read_cb, closure);
685
686         g_object_unref (stream);
687
688         return;
689
690 out:
691         g_simple_async_result_complete (closure->result);
692
693         g_clear_error (&error);
694         tp_clear_object (&stream);
695         pixbuf_avatar_from_individual_closure_free (closure);
696 }
697
698 void
699 empathy_pixbuf_avatar_from_individual_scaled_async (
700                 FolksIndividual     *individual,
701                 gint                 width,
702                 gint                 height,
703                 GCancellable        *cancellable,
704                 GAsyncReadyCallback  callback,
705                 gpointer             user_data)
706 {
707         GLoadableIcon *avatar_icon;
708         GSimpleAsyncResult *result;
709         PixbufAvatarFromIndividualClosure *closure;
710
711         result = g_simple_async_result_new (G_OBJECT (individual),
712                         callback, user_data,
713                         empathy_pixbuf_avatar_from_individual_scaled_async);
714
715         avatar_icon =
716                 folks_avatar_details_get_avatar (FOLKS_AVATAR_DETAILS (individual));
717         if (avatar_icon == NULL)
718                 goto out;
719
720         closure = pixbuf_avatar_from_individual_closure_new (individual, result,
721                                                              width, height,
722                                                              cancellable);
723         if (closure == NULL)
724                 goto out;
725
726         g_loadable_icon_load_async (avatar_icon, width, cancellable,
727                         avatar_icon_load_cb, closure);
728
729         g_object_unref (result);
730
731         return;
732
733 out:
734         g_simple_async_result_set_op_res_gpointer (result, NULL, NULL);
735         g_simple_async_result_complete (result);
736         g_object_unref (result);
737 }
738
739 /* Return a ref on the GdkPixbuf */
740 GdkPixbuf *
741 empathy_pixbuf_avatar_from_individual_scaled_finish (
742                 FolksIndividual *individual,
743                 GAsyncResult *result,
744                 GError **error)
745 {
746         GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
747         gboolean result_valid;
748         GdkPixbuf *pixbuf;
749
750         g_return_val_if_fail (FOLKS_IS_INDIVIDUAL (individual), NULL);
751         g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), NULL);
752
753         if (g_simple_async_result_propagate_error (simple, error))
754                 return NULL;
755
756         result_valid = g_simple_async_result_is_valid (result,
757                         G_OBJECT (individual),
758                         empathy_pixbuf_avatar_from_individual_scaled_async);
759         g_return_val_if_fail (result_valid, NULL);
760
761         pixbuf = g_simple_async_result_get_op_res_gpointer (simple);
762         return pixbuf != NULL ? g_object_ref (pixbuf) : NULL;
763 }
764
765 GdkPixbuf *
766 empathy_pixbuf_contact_status_icon (EmpathyContact *contact,
767                                    gboolean       show_protocol)
768 {
769         const gchar *icon_name;
770
771         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
772
773         icon_name = empathy_icon_name_for_contact (contact);
774
775         if (icon_name == NULL) {
776                 return NULL;
777         }
778         return empathy_pixbuf_contact_status_icon_with_icon_name (contact,
779             icon_name,
780             show_protocol);
781 }
782
783 GdkPixbuf *
784 empathy_pixbuf_contact_status_icon_with_icon_name (EmpathyContact *contact,
785                                           const gchar    *icon_name,
786                                           gboolean       show_protocol)
787 {
788         GdkPixbuf *pix_status;
789         GdkPixbuf *pix_protocol;
790         gchar     *icon_filename;
791         gint       height, width;
792         gint       numerator, denominator;
793
794         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact) ||
795                         (show_protocol == FALSE), NULL);
796         g_return_val_if_fail (icon_name != NULL, NULL);
797
798         numerator = 3;
799         denominator = 4;
800
801         icon_filename = empathy_filename_from_icon_name (icon_name,
802                                                          GTK_ICON_SIZE_MENU);
803         if (icon_filename == NULL) {
804                 DEBUG ("icon name: %s could not be found\n", icon_name);
805                 return NULL;
806         }
807
808         pix_status = gdk_pixbuf_new_from_file (icon_filename, NULL);
809
810         if (pix_status == NULL) {
811                 DEBUG ("Could not open icon %s\n", icon_filename);
812                 g_free (icon_filename);
813                 return NULL;
814         }
815
816         g_free (icon_filename);
817
818         if (!show_protocol)
819                 return pix_status;
820
821         height = gdk_pixbuf_get_height (pix_status);
822         width = gdk_pixbuf_get_width (pix_status);
823
824         pix_protocol = empathy_pixbuf_protocol_from_contact_scaled (contact,
825                                                                     width * numerator / denominator,
826                                                                     height * numerator / denominator);
827
828         if (pix_protocol == NULL) {
829                 return pix_status;
830         }
831         gdk_pixbuf_composite (pix_protocol, pix_status,
832             0, height - height * numerator / denominator,
833             width * numerator / denominator, height * numerator / denominator,
834             0, height - height * numerator / denominator,
835             1, 1,
836             GDK_INTERP_BILINEAR, 255);
837
838         g_object_unref (pix_protocol);
839
840         return pix_status;
841 }
842
843 GdkPixbuf *
844 empathy_pixbuf_protocol_from_contact_scaled (EmpathyContact *contact,
845                                           gint           width,
846                                           gint           height)
847 {
848         TpAccount *account;
849         gchar     *filename;
850         GdkPixbuf *pixbuf = NULL;
851
852         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
853
854         account = empathy_contact_get_account (contact);
855         filename = empathy_filename_from_icon_name (tp_account_get_icon_name (account),
856                                                     GTK_ICON_SIZE_MENU);
857         if (filename != NULL) {
858                 pixbuf = gdk_pixbuf_new_from_file_at_size (filename, width, height, NULL);
859                 g_free (filename);
860         }
861
862         return pixbuf;
863 }
864
865 GdkPixbuf *
866 empathy_pixbuf_scale_down_if_necessary (GdkPixbuf *pixbuf, gint max_size)
867 {
868         gint      width, height;
869         gdouble   factor;
870
871         width = gdk_pixbuf_get_width (pixbuf);
872         height = gdk_pixbuf_get_height (pixbuf);
873
874         if (width > 0 && (width > max_size || height > max_size)) {
875                 factor = (gdouble) max_size / MAX (width, height);
876
877                 width = width * factor;
878                 height = height * factor;
879
880                 return gdk_pixbuf_scale_simple (pixbuf,
881                                                 width, height,
882                                                 GDK_INTERP_HYPER);
883         }
884
885         return g_object_ref (pixbuf);
886 }
887
888 GdkPixbuf *
889 empathy_pixbuf_from_icon_name_sized (const gchar *icon_name,
890                                      gint size)
891 {
892         GtkIconTheme *theme;
893         GdkPixbuf *pixbuf;
894         GError *error = NULL;
895
896         if (!icon_name) {
897                 return NULL;
898         }
899
900         theme = gtk_icon_theme_get_default ();
901
902         pixbuf = gtk_icon_theme_load_icon (theme,
903                                            icon_name,
904                                            size,
905                                            0,
906                                            &error);
907         if (error) {
908                 DEBUG ("Error loading icon: %s", error->message);
909                 g_clear_error (&error);
910         }
911
912         return pixbuf;
913 }
914
915 GdkPixbuf *
916 empathy_pixbuf_from_icon_name (const gchar *icon_name,
917                                GtkIconSize  icon_size)
918 {
919         gint  w, h;
920         gint  size = 48;
921
922         if (!icon_name) {
923                 return NULL;
924         }
925
926         if (gtk_icon_size_lookup (icon_size, &w, &h)) {
927                 size = (w + h) / 2;
928         }
929
930         return empathy_pixbuf_from_icon_name_sized (icon_name, size);
931 }
932
933 gchar *
934 empathy_filename_from_icon_name (const gchar *icon_name,
935                                  GtkIconSize  icon_size)
936 {
937         GtkIconTheme *icon_theme;
938         GtkIconInfo  *icon_info;
939         gint          w, h;
940         gint          size = 48;
941         gchar        *ret;
942
943         icon_theme = gtk_icon_theme_get_default ();
944
945         if (gtk_icon_size_lookup (icon_size, &w, &h)) {
946                 size = (w + h) / 2;
947         }
948
949         icon_info = gtk_icon_theme_lookup_icon (icon_theme, icon_name, size, 0);
950         ret = g_strdup (gtk_icon_info_get_filename (icon_info));
951         gtk_icon_info_free (icon_info);
952
953         return ret;
954 }
955
956 /* Stolen from GtkSourceView, hence the weird intendation. Please keep it like
957  * that to make it easier to apply changes from the original code.
958  */
959 #define GTK_TEXT_UNKNOWN_CHAR 0xFFFC
960
961 /* this function acts like g_utf8_offset_to_pointer() except that if it finds a
962  * decomposable character it consumes the decomposition length from the given
963  * offset.  So it's useful when the offset was calculated for the normalized
964  * version of str, but we need a pointer to str itself. */
965 static const gchar *
966 pointer_from_offset_skipping_decomp (const gchar *str, gint offset)
967 {
968         gchar *casefold, *normal;
969         const gchar *p, *q;
970
971         p = str;
972         while (offset > 0)
973         {
974                 q = g_utf8_next_char (p);
975                 casefold = g_utf8_casefold (p, q - p);
976                 normal = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
977                 offset -= g_utf8_strlen (normal, -1);
978                 g_free (casefold);
979                 g_free (normal);
980                 p = q;
981         }
982         return p;
983 }
984
985 static const gchar *
986 g_utf8_strcasestr (const gchar *haystack, const gchar *needle)
987 {
988         gsize needle_len;
989         gsize haystack_len;
990         const gchar *ret = NULL;
991         gchar *p;
992         gchar *casefold;
993         gchar *caseless_haystack;
994         gint i;
995
996         g_return_val_if_fail (haystack != NULL, NULL);
997         g_return_val_if_fail (needle != NULL, NULL);
998
999         casefold = g_utf8_casefold (haystack, -1);
1000         caseless_haystack = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1001         g_free (casefold);
1002
1003         needle_len = g_utf8_strlen (needle, -1);
1004         haystack_len = g_utf8_strlen (caseless_haystack, -1);
1005
1006         if (needle_len == 0)
1007         {
1008                 ret = (gchar *) haystack;
1009                 goto finally_1;
1010         }
1011
1012         if (haystack_len < needle_len)
1013         {
1014                 ret = NULL;
1015                 goto finally_1;
1016         }
1017
1018         p = (gchar *) caseless_haystack;
1019         needle_len = strlen (needle);
1020         i = 0;
1021
1022         while (*p)
1023         {
1024                 if ((strncmp (p, needle, needle_len) == 0))
1025                 {
1026                         ret = pointer_from_offset_skipping_decomp (haystack, i);
1027                         goto finally_1;
1028                 }
1029
1030                 p = g_utf8_next_char (p);
1031                 i++;
1032         }
1033
1034 finally_1:
1035         g_free (caseless_haystack);
1036
1037         return ret;
1038 }
1039
1040 static gboolean
1041 g_utf8_caselessnmatch (const char *s1, const char *s2,
1042                        gssize n1, gssize n2)
1043 {
1044         gchar *casefold;
1045         gchar *normalized_s1;
1046         gchar *normalized_s2;
1047         gint len_s1;
1048         gint len_s2;
1049         gboolean ret = FALSE;
1050
1051         g_return_val_if_fail (s1 != NULL, FALSE);
1052         g_return_val_if_fail (s2 != NULL, FALSE);
1053         g_return_val_if_fail (n1 > 0, FALSE);
1054         g_return_val_if_fail (n2 > 0, FALSE);
1055
1056         casefold = g_utf8_casefold (s1, n1);
1057         normalized_s1 = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1058         g_free (casefold);
1059
1060         casefold = g_utf8_casefold (s2, n2);
1061         normalized_s2 = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1062         g_free (casefold);
1063
1064         len_s1 = strlen (normalized_s1);
1065         len_s2 = strlen (normalized_s2);
1066
1067         if (len_s1 < len_s2)
1068                 goto finally_2;
1069
1070         ret = (strncmp (normalized_s1, normalized_s2, len_s2) == 0);
1071
1072 finally_2:
1073         g_free (normalized_s1);
1074         g_free (normalized_s2);
1075
1076         return ret;
1077 }
1078
1079 static void
1080 forward_chars_with_skipping (GtkTextIter *iter,
1081                              gint         count,
1082                              gboolean     skip_invisible,
1083                              gboolean     skip_nontext,
1084                              gboolean     skip_decomp)
1085 {
1086         gint i;
1087
1088         g_return_if_fail (count >= 0);
1089
1090         i = count;
1091
1092         while (i > 0)
1093         {
1094                 gboolean ignored = FALSE;
1095
1096                 /* minimal workaround to avoid the infinite loop of bug #168247.
1097                  * It doesn't fix the problemjust the symptom...
1098                  */
1099                 if (gtk_text_iter_is_end (iter))
1100                         return;
1101
1102                 if (skip_nontext && gtk_text_iter_get_char (iter) == GTK_TEXT_UNKNOWN_CHAR)
1103                         ignored = TRUE;
1104
1105                 if (!ignored && skip_invisible &&
1106                     /* _gtk_text_btree_char_is_invisible (iter)*/ FALSE)
1107                         ignored = TRUE;
1108
1109                 if (!ignored && skip_decomp)
1110                 {
1111                         /* being UTF8 correct sucks; this accounts for extra
1112                            offsets coming from canonical decompositions of
1113                            UTF8 characters (e.g. accented characters) which
1114                            g_utf8_normalize () performs */
1115                         gchar *normal;
1116                         gchar buffer[6];
1117                         gint buffer_len;
1118
1119                         buffer_len = g_unichar_to_utf8 (gtk_text_iter_get_char (iter), buffer);
1120                         normal = g_utf8_normalize (buffer, buffer_len, G_NORMALIZE_NFD);
1121                         i -= (g_utf8_strlen (normal, -1) - 1);
1122                         g_free (normal);
1123                 }
1124
1125                 gtk_text_iter_forward_char (iter);
1126
1127                 if (!ignored)
1128                         --i;
1129         }
1130 }
1131
1132 static gboolean
1133 lines_match (const GtkTextIter *start,
1134              const gchar      **lines,
1135              gboolean           visible_only,
1136              gboolean           slice,
1137              GtkTextIter       *match_start,
1138              GtkTextIter       *match_end)
1139 {
1140         GtkTextIter next;
1141         gchar *line_text;
1142         const gchar *found;
1143         gint offset;
1144
1145         if (*lines == NULL || **lines == '\0')
1146         {
1147                 if (match_start)
1148                         *match_start = *start;
1149                 if (match_end)
1150                         *match_end = *start;
1151                 return TRUE;
1152         }
1153
1154         next = *start;
1155         gtk_text_iter_forward_line (&next);
1156
1157         /* No more text in buffer, but *lines is nonempty */
1158         if (gtk_text_iter_equal (start, &next))
1159                 return FALSE;
1160
1161         if (slice)
1162         {
1163                 if (visible_only)
1164                         line_text = gtk_text_iter_get_visible_slice (start, &next);
1165                 else
1166                         line_text = gtk_text_iter_get_slice (start, &next);
1167         }
1168         else
1169         {
1170                 if (visible_only)
1171                         line_text = gtk_text_iter_get_visible_text (start, &next);
1172                 else
1173                         line_text = gtk_text_iter_get_text (start, &next);
1174         }
1175
1176         if (match_start) /* if this is the first line we're matching */
1177         {
1178                 found = g_utf8_strcasestr (line_text, *lines);
1179         }
1180         else
1181         {
1182                 /* If it's not the first line, we have to match from the
1183                  * start of the line.
1184                  */
1185                 if (g_utf8_caselessnmatch (line_text, *lines, strlen (line_text),
1186                                            strlen (*lines)))
1187                         found = line_text;
1188                 else
1189                         found = NULL;
1190         }
1191
1192         if (found == NULL)
1193         {
1194                 g_free (line_text);
1195                 return FALSE;
1196         }
1197
1198         /* Get offset to start of search string */
1199         offset = g_utf8_strlen (line_text, found - line_text);
1200
1201         next = *start;
1202
1203         /* If match start needs to be returned, set it to the
1204          * start of the search string.
1205          */
1206         forward_chars_with_skipping (&next, offset, visible_only, !slice, FALSE);
1207         if (match_start)
1208         {
1209                 *match_start = next;
1210         }
1211
1212         /* Go to end of search string */
1213         forward_chars_with_skipping (&next, g_utf8_strlen (*lines, -1), visible_only, !slice, TRUE);
1214
1215         g_free (line_text);
1216
1217         ++lines;
1218
1219         if (match_end)
1220                 *match_end = next;
1221
1222         /* pass NULL for match_start, since we don't need to find the
1223          * start again.
1224          */
1225         return lines_match (&next, lines, visible_only, slice, NULL, match_end);
1226 }
1227
1228 /* strsplit () that retains the delimiter as part of the string. */
1229 static gchar **
1230 strbreakup (const char *string,
1231             const char *delimiter,
1232             gint        max_tokens)
1233 {
1234         GSList *string_list = NULL, *slist;
1235         gchar **str_array, *s, *casefold, *new_string;
1236         guint i, n = 1;
1237
1238         g_return_val_if_fail (string != NULL, NULL);
1239         g_return_val_if_fail (delimiter != NULL, NULL);
1240
1241         if (max_tokens < 1)
1242                 max_tokens = G_MAXINT;
1243
1244         s = strstr (string, delimiter);
1245         if (s)
1246         {
1247                 guint delimiter_len = strlen (delimiter);
1248
1249                 do
1250                 {
1251                         guint len;
1252
1253                         len = s - string + delimiter_len;
1254                         new_string = g_new (gchar, len + 1);
1255                         strncpy (new_string, string, len);
1256                         new_string[len] = 0;
1257                         casefold = g_utf8_casefold (new_string, -1);
1258                         g_free (new_string);
1259                         new_string = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1260                         g_free (casefold);
1261                         string_list = g_slist_prepend (string_list, new_string);
1262                         n++;
1263                         string = s + delimiter_len;
1264                         s = strstr (string, delimiter);
1265                 } while (--max_tokens && s);
1266         }
1267
1268         if (*string)
1269         {
1270                 n++;
1271                 casefold = g_utf8_casefold (string, -1);
1272                 new_string = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1273                 g_free (casefold);
1274                 string_list = g_slist_prepend (string_list, new_string);
1275         }
1276
1277         str_array = g_new (gchar*, n);
1278
1279         i = n - 1;
1280
1281         str_array[i--] = NULL;
1282         for (slist = string_list; slist; slist = slist->next)
1283                 str_array[i--] = slist->data;
1284
1285         g_slist_free (string_list);
1286
1287         return str_array;
1288 }
1289
1290 gboolean
1291 empathy_text_iter_forward_search (const GtkTextIter   *iter,
1292                                  const gchar         *str,
1293                                  GtkTextIter         *match_start,
1294                                  GtkTextIter         *match_end,
1295                                  const GtkTextIter   *limit)
1296 {
1297         gchar **lines = NULL;
1298         GtkTextIter match;
1299         gboolean retval = FALSE;
1300         GtkTextIter search;
1301         gboolean visible_only;
1302         gboolean slice;
1303
1304         g_return_val_if_fail (iter != NULL, FALSE);
1305         g_return_val_if_fail (str != NULL, FALSE);
1306
1307         if (limit && gtk_text_iter_compare (iter, limit) >= 0)
1308                 return FALSE;
1309
1310         if (*str == '\0') {
1311                 /* If we can move one char, return the empty string there */
1312                 match = *iter;
1313
1314                 if (gtk_text_iter_forward_char (&match)) {
1315                         if (limit && gtk_text_iter_equal (&match, limit)) {
1316                                 return FALSE;
1317                         }
1318
1319                         if (match_start) {
1320                                 *match_start = match;
1321                         }
1322                         if (match_end) {
1323                                 *match_end = match;
1324                         }
1325                         return TRUE;
1326                 } else {
1327                         return FALSE;
1328                 }
1329         }
1330
1331         visible_only = TRUE;
1332         slice = FALSE;
1333
1334         /* locate all lines */
1335         lines = strbreakup (str, "\n", -1);
1336
1337         search = *iter;
1338
1339         do {
1340                 /* This loop has an inefficient worst-case, where
1341                  * gtk_text_iter_get_text () is called repeatedly on
1342                  * a single line.
1343                  */
1344                 GtkTextIter end;
1345
1346                 if (limit && gtk_text_iter_compare (&search, limit) >= 0) {
1347                         break;
1348                 }
1349
1350                 if (lines_match (&search, (const gchar**)lines,
1351                                  visible_only, slice, &match, &end)) {
1352                         if (limit == NULL ||
1353                             (limit && gtk_text_iter_compare (&end, limit) <= 0)) {
1354                                 retval = TRUE;
1355
1356                                 if (match_start) {
1357                                         *match_start = match;
1358                                 }
1359                                 if (match_end) {
1360                                         *match_end = end;
1361                                 }
1362                         }
1363                         break;
1364                 }
1365         } while (gtk_text_iter_forward_line (&search));
1366
1367         g_strfreev ((gchar **) lines);
1368
1369         return retval;
1370 }
1371
1372 static const gchar *
1373 g_utf8_strrcasestr (const gchar *haystack, const gchar *needle)
1374 {
1375         gsize needle_len;
1376         gsize haystack_len;
1377         const gchar *ret = NULL;
1378         gchar *p;
1379         gchar *casefold;
1380         gchar *caseless_haystack;
1381         gint i;
1382
1383         g_return_val_if_fail (haystack != NULL, NULL);
1384         g_return_val_if_fail (needle != NULL, NULL);
1385
1386         casefold = g_utf8_casefold (haystack, -1);
1387         caseless_haystack = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1388         g_free (casefold);
1389
1390         needle_len = g_utf8_strlen (needle, -1);
1391         haystack_len = g_utf8_strlen (caseless_haystack, -1);
1392
1393         if (needle_len == 0)
1394         {
1395                 ret = (gchar *) haystack;
1396                 goto finally_1;
1397         }
1398
1399         if (haystack_len < needle_len)
1400         {
1401                 ret = NULL;
1402                 goto finally_1;
1403         }
1404
1405         i = haystack_len - needle_len;
1406         p = g_utf8_offset_to_pointer (caseless_haystack, i);
1407         needle_len = strlen (needle);
1408
1409         while (p >= caseless_haystack)
1410         {
1411                 if (strncmp (p, needle, needle_len) == 0)
1412                 {
1413                         ret = pointer_from_offset_skipping_decomp (haystack, i);
1414                         goto finally_1;
1415                 }
1416
1417                 p = g_utf8_prev_char (p);
1418                 i--;
1419         }
1420
1421 finally_1:
1422         g_free (caseless_haystack);
1423
1424         return ret;
1425 }
1426
1427 static gboolean
1428 backward_lines_match (const GtkTextIter *start,
1429                       const gchar      **lines,
1430                       gboolean           visible_only,
1431                       gboolean           slice,
1432                       GtkTextIter       *match_start,
1433                       GtkTextIter       *match_end)
1434 {
1435         GtkTextIter line, next;
1436         gchar *line_text;
1437         const gchar *found;
1438         gint offset;
1439
1440         if (*lines == NULL || **lines == '\0')
1441         {
1442                 if (match_start)
1443                         *match_start = *start;
1444                 if (match_end)
1445                         *match_end = *start;
1446                 return TRUE;
1447         }
1448
1449         line = next = *start;
1450         if (gtk_text_iter_get_line_offset (&next) == 0)
1451         {
1452                 if (!gtk_text_iter_backward_line (&next))
1453                         return FALSE;
1454         }
1455         else
1456                 gtk_text_iter_set_line_offset (&next, 0);
1457
1458         if (slice)
1459         {
1460                 if (visible_only)
1461                         line_text = gtk_text_iter_get_visible_slice (&next, &line);
1462                 else
1463                         line_text = gtk_text_iter_get_slice (&next, &line);
1464         }
1465         else
1466         {
1467                 if (visible_only)
1468                         line_text = gtk_text_iter_get_visible_text (&next, &line);
1469                 else
1470                         line_text = gtk_text_iter_get_text (&next, &line);
1471         }
1472
1473         if (match_start) /* if this is the first line we're matching */
1474         {
1475                 found = g_utf8_strrcasestr (line_text, *lines);
1476         }
1477         else
1478         {
1479                 /* If it's not the first line, we have to match from the
1480                  * start of the line.
1481                  */
1482                 if (g_utf8_caselessnmatch (line_text, *lines, strlen (line_text),
1483                                            strlen (*lines)))
1484                         found = line_text;
1485                 else
1486                         found = NULL;
1487         }
1488
1489         if (found == NULL)
1490         {
1491                 g_free (line_text);
1492                 return FALSE;
1493         }
1494
1495         /* Get offset to start of search string */
1496         offset = g_utf8_strlen (line_text, found - line_text);
1497
1498         forward_chars_with_skipping (&next, offset, visible_only, !slice, FALSE);
1499
1500         /* If match start needs to be returned, set it to the
1501          * start of the search string.
1502          */
1503         if (match_start)
1504         {
1505                 *match_start = next;
1506         }
1507
1508         /* Go to end of search string */
1509         forward_chars_with_skipping (&next, g_utf8_strlen (*lines, -1), visible_only, !slice, TRUE);
1510
1511         g_free (line_text);
1512
1513         ++lines;
1514
1515         if (match_end)
1516                 *match_end = next;
1517
1518         /* try to match the rest of the lines forward, passing NULL
1519          * for match_start so lines_match will try to match the entire
1520          * line */
1521         return lines_match (&next, lines, visible_only,
1522                             slice, NULL, match_end);
1523 }
1524
1525 gboolean
1526 empathy_text_iter_backward_search (const GtkTextIter   *iter,
1527                                   const gchar         *str,
1528                                   GtkTextIter         *match_start,
1529                                   GtkTextIter         *match_end,
1530                                   const GtkTextIter   *limit)
1531 {
1532         gchar **lines = NULL;
1533         GtkTextIter match;
1534         gboolean retval = FALSE;
1535         GtkTextIter search;
1536         gboolean visible_only;
1537         gboolean slice;
1538
1539         g_return_val_if_fail (iter != NULL, FALSE);
1540         g_return_val_if_fail (str != NULL, FALSE);
1541
1542         if (limit && gtk_text_iter_compare (iter, limit) <= 0)
1543                 return FALSE;
1544
1545         if (*str == '\0')
1546         {
1547                 /* If we can move one char, return the empty string there */
1548                 match = *iter;
1549
1550                 if (gtk_text_iter_backward_char (&match))
1551                 {
1552                         if (limit && gtk_text_iter_equal (&match, limit))
1553                                 return FALSE;
1554
1555                         if (match_start)
1556                                 *match_start = match;
1557                         if (match_end)
1558                                 *match_end = match;
1559                         return TRUE;
1560                 }
1561                 else
1562                 {
1563                         return FALSE;
1564                 }
1565         }
1566
1567         visible_only = TRUE;
1568         slice = TRUE;
1569
1570         /* locate all lines */
1571         lines = strbreakup (str, "\n", -1);
1572
1573         search = *iter;
1574
1575         while (TRUE)
1576         {
1577                 /* This loop has an inefficient worst-case, where
1578                  * gtk_text_iter_get_text () is called repeatedly on
1579                  * a single line.
1580                  */
1581                 GtkTextIter end;
1582
1583                 if (limit && gtk_text_iter_compare (&search, limit) <= 0)
1584                         break;
1585
1586                 if (backward_lines_match (&search, (const gchar**)lines,
1587                                           visible_only, slice, &match, &end))
1588                 {
1589                         if (limit == NULL || (limit &&
1590                                               gtk_text_iter_compare (&end, limit) > 0))
1591                         {
1592                                 retval = TRUE;
1593
1594                                 if (match_start)
1595                                         *match_start = match;
1596                                 if (match_end)
1597                                         *match_end = end;
1598                         }
1599                         break;
1600                 }
1601
1602                 if (gtk_text_iter_get_line_offset (&search) == 0)
1603                 {
1604                         if (!gtk_text_iter_backward_line (&search))
1605                                 break;
1606                 }
1607                 else
1608                 {
1609                         gtk_text_iter_set_line_offset (&search, 0);
1610                 }
1611         }
1612
1613         g_strfreev ((gchar **) lines);
1614
1615         return retval;
1616 }
1617
1618 /* Takes care of moving the window to the current workspace. */
1619 void
1620 empathy_window_present_with_time (GtkWindow *window,
1621                         guint32 timestamp)
1622 {
1623         GdkWindow *gdk_window;
1624
1625         g_return_if_fail (GTK_IS_WINDOW (window));
1626
1627         /* Move the window to the current workspace before trying to show it.
1628          * This is the behaviour people expect when clicking on the statusbar icon. */
1629         gdk_window = gtk_widget_get_window (GTK_WIDGET (window));
1630         if (gdk_window) {
1631                 gint x, y;
1632                 gint w, h;
1633
1634                 /* Has no effect if the WM has viewports, like compiz */
1635                 gdk_x11_window_move_to_current_desktop (gdk_window);
1636
1637                 /* If window is still off-screen, hide it to force it to
1638                  * reposition on the current workspace. */
1639                 gtk_window_get_position (window, &x, &y);
1640                 gtk_window_get_size (window, &w, &h);
1641                 if (!EMPATHY_RECT_IS_ON_SCREEN (x, y, w, h))
1642                         gtk_widget_hide (GTK_WIDGET (window));
1643         }
1644
1645         if (timestamp == GDK_CURRENT_TIME)
1646                 gtk_window_present (window);
1647         else
1648                 gtk_window_present_with_time (window, timestamp);
1649 }
1650
1651 void
1652 empathy_window_present (GtkWindow *window)
1653 {
1654   empathy_window_present_with_time (window, gtk_get_current_event_time ());
1655 }
1656
1657 GtkWindow *
1658 empathy_get_toplevel_window (GtkWidget *widget)
1659 {
1660         GtkWidget *toplevel;
1661
1662         g_return_val_if_fail (GTK_IS_WIDGET (widget), NULL);
1663
1664         toplevel = gtk_widget_get_toplevel (widget);
1665         if (GTK_IS_WINDOW (toplevel) &&
1666             gtk_widget_is_toplevel (toplevel)) {
1667                 return GTK_WINDOW (toplevel);
1668         }
1669
1670         return NULL;
1671 }
1672
1673 /** empathy_make_absolute_url_len:
1674  * @url: an url
1675  * @len: a length
1676  *
1677  * Same as #empathy_make_absolute_url but for a limited string length
1678  */
1679 gchar *
1680 empathy_make_absolute_url_len (const gchar *url,
1681                                guint len)
1682 {
1683         g_return_val_if_fail (url != NULL, NULL);
1684
1685         if (g_str_has_prefix (url, "ghelp:") ||
1686             g_str_has_prefix (url, "mailto:") ||
1687             strstr (url, ":/")) {
1688                 return g_strndup (url, len);
1689         }
1690
1691         if (strstr (url, "@")) {
1692                 return g_strdup_printf ("mailto:%.*s", len, url);
1693         }
1694
1695         return g_strdup_printf ("http://%.*s", len, url);
1696 }
1697
1698 /** empathy_make_absolute_url:
1699  * @url: an url
1700  *
1701  * The URL opening code can't handle schemeless strings, so we try to be
1702  * smart and add http if there is no scheme or doesn't look like a mail
1703  * address. This should work in most cases, and let us click on strings
1704  * like "www.gnome.org".
1705  *
1706  * Returns: a newly allocated url with proper mailto: or http:// prefix, use
1707  * g_free when your are done with it
1708  */
1709 gchar *
1710 empathy_make_absolute_url (const gchar *url)
1711 {
1712         return empathy_make_absolute_url_len (url, strlen (url));
1713 }
1714
1715 void
1716 empathy_url_show (GtkWidget *parent,
1717                   const char *url)
1718 {
1719         gchar  *real_url;
1720         GError *error = NULL;
1721
1722         g_return_if_fail (parent == NULL || GTK_IS_WIDGET (parent));
1723         g_return_if_fail (url != NULL);
1724
1725         real_url = empathy_make_absolute_url (url);
1726
1727         gtk_show_uri (parent ? gtk_widget_get_screen (parent) : NULL, real_url,
1728                       gtk_get_current_event_time (), &error);
1729
1730         if (error) {
1731                 GtkWidget *dialog;
1732
1733                 dialog = gtk_message_dialog_new (NULL, 0,
1734                                                  GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,
1735                                                  _("Unable to open URI"));
1736                 gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
1737                                                           "%s", error->message);
1738
1739                 g_signal_connect (dialog, "response",
1740                                   G_CALLBACK (gtk_widget_destroy),
1741                                   NULL);
1742                 gtk_window_present (GTK_WINDOW (dialog));
1743
1744                 g_clear_error (&error);
1745         }
1746
1747         g_free (real_url);
1748 }
1749
1750 void
1751 empathy_send_file (EmpathyContact *contact, GFile *file)
1752 {
1753         EmpathyFTFactory *factory;
1754         GtkRecentManager *manager;
1755         gchar *uri;
1756
1757         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1758         g_return_if_fail (G_IS_FILE (file));
1759
1760         factory = empathy_ft_factory_dup_singleton ();
1761
1762         empathy_ft_factory_new_transfer_outgoing (factory, contact, file,
1763                 empathy_get_current_action_time ());
1764
1765         uri = g_file_get_uri (file);
1766         manager = gtk_recent_manager_get_default ();
1767         gtk_recent_manager_add_item (manager, uri);
1768         g_free (uri);
1769
1770         g_object_unref (factory);
1771 }
1772
1773 void
1774 empathy_send_file_from_uri_list (EmpathyContact *contact, const gchar *uri_list)
1775 {
1776         const gchar *nl;
1777         GFile *file;
1778
1779         /* Only handle a single file for now.  It would be wicked cool to be
1780            able to do multiple files, offering to zip them or whatever like
1781            nautilus-sendto does.  Note that text/uri-list is defined to have
1782            each line terminated by \r\n, but we can be tolerant of applications
1783            that only use \n or don't terminate single-line entries.
1784         */
1785         nl = strstr (uri_list, "\r\n");
1786         if (!nl) {
1787                 nl = strchr (uri_list, '\n');
1788         }
1789         if (nl) {
1790                 gchar *uri = g_strndup (uri_list, nl - uri_list);
1791                 file = g_file_new_for_uri (uri);
1792                 g_free (uri);
1793         }
1794         else {
1795                 file = g_file_new_for_uri (uri_list);
1796         }
1797
1798         empathy_send_file (contact, file);
1799
1800         g_object_unref (file);
1801 }
1802
1803 static void
1804 file_manager_send_file_response_cb (GtkDialog      *widget,
1805                                     gint            response_id,
1806                                     EmpathyContact *contact)
1807 {
1808         GFile *file;
1809
1810         if (response_id == GTK_RESPONSE_OK) {
1811                 file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (widget));
1812
1813                 empathy_send_file (contact, file);
1814
1815                 g_object_unref (file);
1816         }
1817
1818         g_object_unref (contact);
1819         gtk_widget_destroy (GTK_WIDGET (widget));
1820 }
1821
1822 void
1823 empathy_send_file_with_file_chooser (EmpathyContact *contact)
1824 {
1825         GtkWidget               *widget;
1826         GtkWidget               *button;
1827
1828         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1829
1830         DEBUG ("Creating selection file chooser");
1831
1832         widget = gtk_file_chooser_dialog_new (_("Select a file"),
1833                                               NULL,
1834                                               GTK_FILE_CHOOSER_ACTION_OPEN,
1835                                               GTK_STOCK_CANCEL,
1836                                               GTK_RESPONSE_CANCEL,
1837                                               NULL);
1838
1839         /* send button */
1840         button = gtk_button_new_with_mnemonic (_("_Send"));
1841         gtk_button_set_image (GTK_BUTTON (button),
1842                 gtk_image_new_from_icon_name (EMPATHY_IMAGE_DOCUMENT_SEND,
1843                                               GTK_ICON_SIZE_BUTTON));
1844         gtk_widget_show (button);
1845         gtk_dialog_add_action_widget (GTK_DIALOG (widget), button,
1846                                       GTK_RESPONSE_OK);
1847         gtk_widget_set_can_default (button, TRUE);
1848         gtk_dialog_set_default_response (GTK_DIALOG (widget),
1849                                          GTK_RESPONSE_OK);
1850
1851         gtk_file_chooser_set_local_only (GTK_FILE_CHOOSER (widget), FALSE);
1852
1853         gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (widget),
1854                 g_get_home_dir ());
1855
1856         g_signal_connect (widget, "response",
1857                           G_CALLBACK (file_manager_send_file_response_cb),
1858                           g_object_ref (contact));
1859
1860         gtk_widget_show (widget);
1861 }
1862
1863 static void
1864 file_manager_receive_file_response_cb (GtkDialog *dialog,
1865                                        GtkResponseType response,
1866                                        EmpathyFTHandler *handler)
1867 {
1868         EmpathyFTFactory *factory;
1869         GFile *file;
1870
1871         if (response == GTK_RESPONSE_OK) {
1872                 GFile *parent;
1873                 GFileInfo *info;
1874                 guint64 free_space, file_size;
1875                 GError *error = NULL;
1876
1877                 file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (dialog));
1878                 parent = g_file_get_parent (file);
1879                 info = g_file_query_filesystem_info (parent,
1880                                 G_FILE_ATTRIBUTE_FILESYSTEM_FREE,
1881                                 NULL, &error);
1882
1883                 g_object_unref (parent);
1884
1885                 if (error != NULL) {
1886                         g_warning ("Error: %s", error->message);
1887
1888                         g_object_unref (file);
1889                         return;
1890                 }
1891
1892                 free_space = g_file_info_get_attribute_uint64 (info,
1893                                 G_FILE_ATTRIBUTE_FILESYSTEM_FREE);
1894                 file_size = empathy_ft_handler_get_total_bytes (handler);
1895
1896                 g_object_unref (info);
1897
1898                 if (file_size > free_space) {
1899                         GtkWidget *message = gtk_message_dialog_new (
1900                                 GTK_WINDOW (dialog),
1901                                 GTK_DIALOG_MODAL,
1902                                 GTK_MESSAGE_ERROR,
1903                                 GTK_BUTTONS_CLOSE,
1904                                 _("Insufficient free space to save file"));
1905                         char *file_size_str, *free_space_str;
1906
1907                         file_size_str = g_format_size_for_display (file_size);
1908                         free_space_str = g_format_size_for_display (free_space);
1909
1910                         gtk_message_dialog_format_secondary_text (
1911                                 GTK_MESSAGE_DIALOG (message),
1912                                 _("%s of free space are required to save this "
1913                                   "file, but only %s is available. Please "
1914                                   "choose another location."),
1915                                 file_size_str, free_space_str);
1916
1917                         gtk_dialog_run (GTK_DIALOG (message));
1918
1919                         g_free (file_size_str);
1920                         g_free (free_space_str);
1921                         gtk_widget_destroy (message);
1922
1923                         g_object_unref (file);
1924
1925                         return;
1926                 }
1927
1928                 factory = empathy_ft_factory_dup_singleton ();
1929
1930                 empathy_ft_factory_set_destination_for_incoming_handler (
1931                                 factory, handler, file);
1932
1933                 g_object_unref (factory);
1934                 g_object_unref (file);
1935         } else {
1936                 /* unref the handler, as we dismissed the file chooser,
1937                  * and refused the transfer.
1938                  */
1939                 g_object_unref (handler);
1940         }
1941
1942         gtk_widget_destroy (GTK_WIDGET (dialog));
1943 }
1944
1945 void
1946 empathy_receive_file_with_file_chooser (EmpathyFTHandler *handler)
1947 {
1948         GtkWidget *widget;
1949         const gchar *dir;
1950         EmpathyContact *contact;
1951         gchar *title;
1952
1953         contact = empathy_ft_handler_get_contact (handler);
1954         g_assert (contact != NULL);
1955
1956         title = g_strdup_printf (_("Incoming file from %s"),
1957                 empathy_contact_get_alias (contact));
1958
1959         widget = gtk_file_chooser_dialog_new (title,
1960                                               NULL,
1961                                               GTK_FILE_CHOOSER_ACTION_SAVE,
1962                                               GTK_STOCK_CANCEL,
1963                                               GTK_RESPONSE_CANCEL,
1964                                               GTK_STOCK_SAVE,
1965                                               GTK_RESPONSE_OK,
1966                                               NULL);
1967         gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (widget),
1968                 empathy_ft_handler_get_filename (handler));
1969         gtk_file_chooser_set_do_overwrite_confirmation
1970                 (GTK_FILE_CHOOSER (widget), TRUE);
1971
1972         dir = g_get_user_special_dir (G_USER_DIRECTORY_DOWNLOAD);
1973         if (dir == NULL)
1974                 /* Fallback to $HOME if $XDG_DOWNLOAD_DIR is not set */
1975                 dir = g_get_home_dir ();
1976
1977         gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (widget), dir);
1978
1979         g_signal_connect (widget, "response",
1980                 G_CALLBACK (file_manager_receive_file_response_cb), handler);
1981
1982         gtk_widget_show (widget);
1983         g_free (title);
1984 }
1985
1986 void
1987 empathy_make_color_whiter (GdkRGBA *color)
1988 {
1989         const GdkRGBA white = { 1.0, 1.0, 1.0, 1.0 };
1990
1991         color->red = (color->red + white.red) / 2;
1992         color->green = (color->green + white.green) / 2;
1993         color->blue = (color->blue + white.blue) / 2;
1994 }
1995
1996 static void
1997 menu_deactivate_cb (GtkMenu *menu,
1998         gpointer user_data)
1999 {
2000         /* FIXME: we shouldn't have to disconnect the signal (bgo #641327) */
2001         g_signal_handlers_disconnect_by_func (menu,
2002                      menu_deactivate_cb, user_data);
2003
2004         gtk_menu_detach (menu);
2005 }
2006
2007 /* Convenient function to create a GtkMenu attached to @attach_to and detach
2008  * it when the menu is not displayed any more. This is useful when creating a
2009  * context menu that we want to get rid as soon as it as been displayed. */
2010 GtkWidget *
2011 empathy_context_menu_new (GtkWidget *attach_to)
2012 {
2013         GtkWidget *menu;
2014
2015         menu = gtk_menu_new ();
2016
2017         gtk_menu_attach_to_widget (GTK_MENU (menu), attach_to, NULL);
2018
2019         /* menu is initially unowned but gtk_menu_attach_to_widget () taked its
2020          * floating ref. We can either wait that @attach_to releases its ref when
2021          * it will be destroyed (when leaving Empathy most of the time) or explicitely
2022          * detach the menu when it's not displayed any more.
2023          * We go for the latter as we don't want to keep useless menus in memory
2024          * during the whole lifetime of Empathy. */
2025         g_signal_connect (menu, "deactivate", G_CALLBACK (menu_deactivate_cb), NULL);
2026
2027         return menu;
2028 }
2029
2030 gint64
2031 empathy_get_current_action_time (void)
2032 {
2033   return (tp_user_action_time_from_x11 (gtk_get_current_event_time ()));
2034 }
2035
2036 /* @words = empathy_live_search_strip_utf8_string (@text);
2037  *
2038  * User has to pass both so we don't have to compute @words ourself each time
2039  * this function is called. */
2040 gboolean
2041 empathy_individual_match_string (FolksIndividual *individual,
2042     const char *text,
2043     GPtrArray *words)
2044 {
2045   const gchar *str;
2046   GeeSet *personas;
2047   GeeIterator *iter;
2048   gboolean retval = FALSE;
2049
2050   /* check alias name */
2051   str = folks_alias_details_get_alias (FOLKS_ALIAS_DETAILS (individual));
2052
2053   if (empathy_live_search_match_words (str, words))
2054     return TRUE;
2055
2056   personas = folks_individual_get_personas (individual);
2057
2058   /* check contact id, remove the @server.com part */
2059   iter = gee_iterable_iterator (GEE_ITERABLE (personas));
2060   while (retval == FALSE && gee_iterator_next (iter))
2061     {
2062       FolksPersona *persona = gee_iterator_get (iter);
2063       const gchar *p;
2064
2065       if (empathy_folks_persona_is_interesting (persona))
2066         {
2067           str = folks_persona_get_display_id (persona);
2068
2069           /* Accept the persona if @text is a full prefix of his ID; that allows
2070            * user to find, say, a jabber contact by typing his JID. */
2071           if (g_str_has_prefix (str, text))
2072             {
2073               retval = TRUE;
2074             }
2075           else
2076             {
2077               gchar *dup_str = NULL;
2078               gboolean visible;
2079
2080               p = strstr (str, "@");
2081               if (p != NULL)
2082                 str = dup_str = g_strndup (str, p - str);
2083
2084               visible = empathy_live_search_match_words (str, words);
2085               g_free (dup_str);
2086               if (visible)
2087                 retval = TRUE;
2088             }
2089         }
2090       g_clear_object (&persona);
2091     }
2092   g_clear_object (&iter);
2093
2094   /* FIXME: Add more rules here, we could check phone numbers in
2095    * contact's vCard for example. */
2096   return retval;
2097 }
2098
2099 static gboolean
2100 dtmf_dialpad_button_pressed_cb (GObject *button,
2101     GtkEntry *entry)
2102 {
2103   GtkEntryBuffer *buffer = gtk_entry_get_buffer (entry);
2104   const gchar *label;
2105
2106   label = g_object_get_data (button, "label");
2107   gtk_entry_buffer_insert_text (buffer, -1, label, -1);
2108
2109   return FALSE;
2110 }
2111
2112 GtkWidget *
2113 empathy_create_dtmf_dialpad (GObject *self,
2114     GCallback dtmf_button_pressed_cb,
2115     GCallback dtmf_button_released_cb)
2116 {
2117   GtkWidget *box, *entry, *table;
2118   int i;
2119   GQuark button_quark;
2120   struct {
2121     const gchar *label;
2122     const gchar *sublabel;
2123     TpDTMFEvent event;
2124   } dtmfbuttons[] = { { "1", "",     TP_DTMF_EVENT_DIGIT_1 },
2125                       { "2", "abc",  TP_DTMF_EVENT_DIGIT_2 },
2126                       { "3", "def",  TP_DTMF_EVENT_DIGIT_3 },
2127                       { "4", "ghi",  TP_DTMF_EVENT_DIGIT_4 },
2128                       { "5", "jkl",  TP_DTMF_EVENT_DIGIT_5 },
2129                       { "6", "mno",  TP_DTMF_EVENT_DIGIT_6 },
2130                       { "7", "pqrs", TP_DTMF_EVENT_DIGIT_7 },
2131                       { "8", "tuv",  TP_DTMF_EVENT_DIGIT_8 },
2132                       { "9", "wxyz", TP_DTMF_EVENT_DIGIT_9 },
2133                       { "#", "",     TP_DTMF_EVENT_HASH },
2134                       { "0", "",     TP_DTMF_EVENT_DIGIT_0 },
2135                       { "*", "",     TP_DTMF_EVENT_ASTERISK },
2136                       { NULL, } };
2137
2138   box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 3);
2139
2140   entry = gtk_entry_new ();
2141   gtk_editable_set_editable (GTK_EDITABLE (entry), FALSE);
2142
2143   gtk_box_pack_start (GTK_BOX (box), entry, FALSE, FALSE, 3);
2144
2145   button_quark = g_quark_from_static_string (EMPATHY_DTMF_BUTTON_ID);
2146
2147   table = gtk_table_new (4, 3, TRUE);
2148
2149   for (i = 0; dtmfbuttons[i].label != NULL; i++)
2150     {
2151       GtkWidget *vbox = gtk_vbox_new (FALSE, 0);
2152       GtkWidget *button = gtk_button_new ();
2153       GtkWidget *label;
2154       gchar *str;
2155
2156       gtk_container_add (GTK_CONTAINER (button), vbox);
2157
2158       /* main label */
2159       label = gtk_label_new ("");
2160       str = g_strdup_printf ("<span size='x-large'>%s</span>",
2161           dtmfbuttons[i].label);
2162       gtk_label_set_markup (GTK_LABEL (label), str);
2163       g_free (str);
2164
2165       g_object_set_data (G_OBJECT (button), "label",
2166           (gpointer) dtmfbuttons[i].label);
2167
2168       gtk_box_pack_start (GTK_BOX (vbox), label, TRUE, TRUE, 3);
2169
2170       /* sub label */
2171       label = gtk_label_new ("");
2172       str = g_strdup_printf (
2173           "<span foreground='#555555'>%s</span>",
2174           dtmfbuttons[i].sublabel);
2175       gtk_label_set_markup (GTK_LABEL (label), str);
2176       g_free (str);
2177
2178       gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, TRUE, 0);
2179
2180       gtk_table_attach (GTK_TABLE (table), button, i % 3, i % 3 + 1,
2181         i/3, i/3 + 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 1, 1);
2182
2183       g_object_set_qdata (G_OBJECT (button), button_quark,
2184         GUINT_TO_POINTER (dtmfbuttons[i].event));
2185
2186       /* To update the GtkEntry */
2187       g_signal_connect (G_OBJECT (button), "pressed",
2188         G_CALLBACK (dtmf_dialpad_button_pressed_cb), entry);
2189
2190       g_signal_connect (G_OBJECT (button), "pressed",
2191         dtmf_button_pressed_cb, self);
2192       g_signal_connect (G_OBJECT (button), "released",
2193         dtmf_button_released_cb, self);
2194     }
2195
2196   gtk_box_pack_start (GTK_BOX (box), table, FALSE, FALSE, 3);
2197
2198   return box;
2199 }
2200
2201 void
2202 empathy_launch_program (const gchar *dir,
2203     const gchar *name,
2204     const gchar *args)
2205 {
2206   GdkDisplay *display;
2207   GError *error = NULL;
2208   gchar *path, *cmd;
2209   GAppInfo *app_info;
2210   GdkAppLaunchContext *context = NULL;
2211
2212   /* Try to run from source directory if possible */
2213   path = g_build_filename (g_getenv ("EMPATHY_SRCDIR"), "src",
2214       name, NULL);
2215
2216   if (!g_file_test (path, G_FILE_TEST_EXISTS))
2217     {
2218       g_free (path);
2219       path = g_build_filename (dir, name, NULL);
2220     }
2221
2222   if (args != NULL)
2223     cmd = g_strconcat (path, " ", args, NULL);
2224   else
2225     cmd = g_strdup (path);
2226
2227   app_info = g_app_info_create_from_commandline (cmd, NULL, 0, &error);
2228   if (app_info == NULL)
2229     {
2230       DEBUG ("Failed to create app info: %s", error->message);
2231       g_error_free (error);
2232       goto out;
2233     }
2234
2235   display = gdk_display_get_default ();
2236   context = gdk_display_get_app_launch_context (display);
2237
2238   if (!g_app_info_launch (app_info, NULL, (GAppLaunchContext *) context,
2239       &error))
2240     {
2241       g_warning ("Failed to launch %s: %s", name, error->message);
2242       g_error_free (error);
2243       goto out;
2244     }
2245
2246 out:
2247   tp_clear_object (&app_info);
2248   tp_clear_object (&context);
2249   g_free (path);
2250   g_free (cmd);
2251 }