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