]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-ui-utils.c
Use the gio async pattern for fetching Individuals' avatars
[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-smiley-manager.h"
48
49 #define DEBUG_FLAG EMPATHY_DEBUG_OTHER
50 #include <libempathy/empathy-debug.h>
51 #include <libempathy/empathy-utils.h>
52 #include <libempathy/empathy-dispatcher.h>
53 #include <libempathy/empathy-idle.h>
54 #include <libempathy/empathy-ft-factory.h>
55
56 void
57 empathy_gtk_init (void)
58 {
59         static gboolean initialized = FALSE;
60
61         if (initialized)
62                 return;
63
64         empathy_init ();
65         gtk_icon_theme_append_search_path (gtk_icon_theme_get_default (),
66                                            PKGDATADIR G_DIR_SEPARATOR_S "icons");
67
68         initialized = TRUE;
69 }
70
71 static GtkBuilder *
72 builder_get_file_valist (const gchar *filename,
73                          const gchar *first_object,
74                          va_list      args)
75 {
76         GtkBuilder  *gui;
77         const gchar *name;
78         GObject    **object_ptr;
79         GError      *error = NULL;
80
81         DEBUG ("Loading file %s", filename);
82
83         gui = gtk_builder_new ();
84         gtk_builder_set_translation_domain (gui, GETTEXT_PACKAGE);
85         if (!gtk_builder_add_from_file (gui, filename, &error)) {
86                 g_critical ("GtkBuilder Error (%s): %s",
87                                 filename, error->message);
88                 g_clear_error (&error);
89                 g_object_unref (gui);
90
91                 /* we need to iterate and set all of the pointers to NULL */
92                 for (name = first_object; name;
93                      name = va_arg (args, const gchar *)) {
94                         object_ptr = va_arg (args, GObject**);
95
96                         *object_ptr = NULL;
97                 }
98
99                 return NULL;
100         }
101
102         for (name = first_object; name; name = va_arg (args, const gchar *)) {
103                 object_ptr = va_arg (args, GObject**);
104
105                 *object_ptr = gtk_builder_get_object (gui, name);
106
107                 if (!*object_ptr) {
108                         g_warning ("File is missing object '%s'.", name);
109                         continue;
110                 }
111         }
112
113         return gui;
114 }
115
116 GtkBuilder *
117 empathy_builder_get_file (const gchar *filename,
118                           const gchar *first_object,
119                           ...)
120 {
121         GtkBuilder *gui;
122         va_list     args;
123
124         va_start (args, first_object);
125         gui = builder_get_file_valist (filename, first_object, args);
126         va_end (args);
127
128         return gui;
129 }
130
131 void
132 empathy_builder_connect (GtkBuilder *gui,
133                          gpointer    user_data,
134                          gchar      *first_object,
135                          ...)
136 {
137         va_list      args;
138         const gchar *name;
139         const gchar *sig;
140         GObject     *object;
141         GCallback    callback;
142
143         va_start (args, first_object);
144         for (name = first_object; name; name = va_arg (args, const gchar *)) {
145                 sig = va_arg (args, const gchar *);
146                 callback = va_arg (args, GCallback);
147
148                 object = gtk_builder_get_object (gui, name);
149                 if (!object) {
150                         g_warning ("File is missing object '%s'.", name);
151                         continue;
152                 }
153
154                 g_signal_connect (object, sig, callback, user_data);
155         }
156
157         va_end (args);
158 }
159
160 GtkWidget *
161 empathy_builder_unref_and_keep_widget (GtkBuilder *gui,
162                                        GtkWidget  *widget)
163 {
164         /* On construction gui sinks the initial reference to widget. When gui
165          * is finalized it will drop its ref to widget. We take our own ref to
166          * prevent widget being finalised. The widget is forced to have a
167          * floating reference, like when it was initially unowned so that it can
168          * be used like any other GtkWidget. */
169
170         g_object_ref (widget);
171         g_object_force_floating (G_OBJECT (widget));
172         g_object_unref (gui);
173
174         return widget;
175 }
176
177 const gchar *
178 empathy_icon_name_for_presence (TpConnectionPresenceType presence)
179 {
180         switch (presence) {
181         case TP_CONNECTION_PRESENCE_TYPE_AVAILABLE:
182                 return EMPATHY_IMAGE_AVAILABLE;
183         case TP_CONNECTION_PRESENCE_TYPE_BUSY:
184                 return EMPATHY_IMAGE_BUSY;
185         case TP_CONNECTION_PRESENCE_TYPE_AWAY:
186                 return EMPATHY_IMAGE_AWAY;
187         case TP_CONNECTION_PRESENCE_TYPE_EXTENDED_AWAY:
188                 if (gtk_icon_theme_has_icon (gtk_icon_theme_get_default (),
189                                              EMPATHY_IMAGE_EXT_AWAY))
190                         return EMPATHY_IMAGE_EXT_AWAY;
191
192                 /* The 'extended-away' icon is not an official one so we fallback to idle if
193                  * it's not implemented */
194                 return EMPATHY_IMAGE_IDLE;
195         case TP_CONNECTION_PRESENCE_TYPE_HIDDEN:
196                 if (gtk_icon_theme_has_icon (gtk_icon_theme_get_default (),
197                                              EMPATHY_IMAGE_HIDDEN))
198                         return EMPATHY_IMAGE_HIDDEN;
199
200                 /* The 'hidden' icon is not an official one so we fallback to offline if
201                  * it's not implemented */
202                 return EMPATHY_IMAGE_OFFLINE;
203         case TP_CONNECTION_PRESENCE_TYPE_OFFLINE:
204         case TP_CONNECTION_PRESENCE_TYPE_ERROR:
205                 return EMPATHY_IMAGE_OFFLINE;
206         case TP_CONNECTION_PRESENCE_TYPE_UNKNOWN:
207                 return EMPATHY_IMAGE_PENDING;
208         case TP_CONNECTION_PRESENCE_TYPE_UNSET:
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 = folks_individual_get_presence_type (individual);
234         presence = empathy_folks_presence_type_to_tp (folks_presence);
235
236         return empathy_icon_name_for_presence (presence);
237 }
238
239 const gchar *
240 empathy_protocol_name_for_contact (EmpathyContact   *contact)
241 {
242         TpAccount     *account;
243
244         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
245
246         account = empathy_contact_get_account (contact);
247         if (account == NULL) {
248                 return NULL;
249         }
250
251         return tp_account_get_icon_name (account);
252 }
253
254 GdkPixbuf *
255 empathy_pixbuf_from_data (gchar *data,
256                           gsize  data_size)
257 {
258         return empathy_pixbuf_from_data_and_mime (data, data_size, NULL);
259 }
260
261 GdkPixbuf *
262 empathy_pixbuf_from_data_and_mime (gchar  *data,
263                                    gsize   data_size,
264                                    gchar **mime_type)
265 {
266         GdkPixbufLoader *loader;
267         GdkPixbufFormat *format;
268         GdkPixbuf       *pixbuf = NULL;
269         gchar          **mime_types;
270         GError          *error = NULL;
271
272         if (!data) {
273                 return NULL;
274         }
275
276         loader = gdk_pixbuf_loader_new ();
277         if (!gdk_pixbuf_loader_write (loader, (guchar *) data, data_size, &error)) {
278                 DEBUG ("Failed to write to pixbuf loader: %s",
279                         error ? error->message : "No error given");
280                 goto out;
281         }
282         if (!gdk_pixbuf_loader_close (loader, &error)) {
283                 DEBUG ("Failed to close pixbuf loader: %s",
284                         error ? error->message : "No error given");
285                 goto out;
286         }
287
288         pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
289         if (pixbuf) {
290                 g_object_ref (pixbuf);
291
292                 if (mime_type != NULL) {
293                         format = gdk_pixbuf_loader_get_format (loader);
294                         mime_types = gdk_pixbuf_format_get_mime_types (format);
295
296                         *mime_type = g_strdup (*mime_types);
297                         if (mime_types[1] != NULL) {
298                                 DEBUG ("Loader supports more than one mime "
299                                         "type! Picking the first one, %s",
300                                         *mime_type);
301                         }
302                         g_strfreev (mime_types);
303                 }
304         }
305
306 out:
307         g_clear_error (&error);
308         g_object_unref (loader);
309
310         return pixbuf;
311 }
312
313 struct SizeData {
314         gint     width;
315         gint     height;
316         gboolean preserve_aspect_ratio;
317 };
318
319 static void
320 pixbuf_from_avatar_size_prepared_cb (GdkPixbufLoader *loader,
321                                      int              width,
322                                      int              height,
323                                      struct SizeData *data)
324 {
325         g_return_if_fail (width > 0 && height > 0);
326
327         if (data->preserve_aspect_ratio && (data->width > 0 || data->height > 0)) {
328                 if (width < data->width && height < data->height) {
329                         width = width;
330                         height = height;
331                 }
332
333                 if (data->width < 0) {
334                         width = width * (double) data->height / (gdouble) height;
335                         height = data->height;
336                 } else if (data->height < 0) {
337                         height = height * (double) data->width / (double) width;
338                         width = data->width;
339                 } else if ((double) height * (double) data->width >
340                            (double) width * (double) data->height) {
341                         width = 0.5 + (double) width * (double) data->height / (double) height;
342                         height = data->height;
343                 } else {
344                         height = 0.5 + (double) height * (double) data->width / (double) width;
345                         width = data->width;
346                 }
347         } else {
348                 if (data->width > 0) {
349                         width = data->width;
350                 }
351
352                 if (data->height > 0) {
353                         height = data->height;
354                 }
355         }
356
357         gdk_pixbuf_loader_set_size (loader, width, height);
358 }
359
360 static void
361 empathy_avatar_pixbuf_roundify (GdkPixbuf *pixbuf)
362 {
363         gint width, height, rowstride;
364         guchar *pixels;
365
366         width = gdk_pixbuf_get_width (pixbuf);
367         height = gdk_pixbuf_get_height (pixbuf);
368         rowstride = gdk_pixbuf_get_rowstride (pixbuf);
369         pixels = gdk_pixbuf_get_pixels (pixbuf);
370
371         if (width < 6 || height < 6) {
372                 return;
373         }
374
375         /* Top left */
376         pixels[3] = 0;
377         pixels[7] = 0x80;
378         pixels[11] = 0xC0;
379         pixels[rowstride + 3] = 0x80;
380         pixels[rowstride * 2 + 3] = 0xC0;
381
382         /* Top right */
383         pixels[width * 4 - 1] = 0;
384         pixels[width * 4 - 5] = 0x80;
385         pixels[width * 4 - 9] = 0xC0;
386         pixels[rowstride + (width * 4) - 1] = 0x80;
387         pixels[(2 * rowstride) + (width * 4) - 1] = 0xC0;
388
389         /* Bottom left */
390         pixels[(height - 1) * rowstride + 3] = 0;
391         pixels[(height - 1) * rowstride + 7] = 0x80;
392         pixels[(height - 1) * rowstride + 11] = 0xC0;
393         pixels[(height - 2) * rowstride + 3] = 0x80;
394         pixels[(height - 3) * rowstride + 3] = 0xC0;
395
396         /* Bottom right */
397         pixels[height * rowstride - 1] = 0;
398         pixels[(height - 1) * rowstride - 1] = 0x80;
399         pixels[(height - 2) * rowstride - 1] = 0xC0;
400         pixels[height * rowstride - 5] = 0x80;
401         pixels[height * rowstride - 9] = 0xC0;
402 }
403
404 static gboolean
405 empathy_gdk_pixbuf_is_opaque (GdkPixbuf *pixbuf)
406 {
407         gint width, height, rowstride, i;
408         guchar *pixels;
409         guchar *row;
410
411         width = gdk_pixbuf_get_width (pixbuf);
412         height = gdk_pixbuf_get_height (pixbuf);
413         rowstride = gdk_pixbuf_get_rowstride (pixbuf);
414         pixels = gdk_pixbuf_get_pixels (pixbuf);
415
416         row = pixels;
417         for (i = 3; i < rowstride; i+=4) {
418                 if (row[i] < 0xfe) {
419                         return FALSE;
420                 }
421         }
422
423         for (i = 1; i < height - 1; i++) {
424                 row = pixels + (i*rowstride);
425                 if (row[3] < 0xfe || row[rowstride-1] < 0xfe) {
426                         return FALSE;
427                 }
428         }
429
430         row = pixels + ((height-1) * rowstride);
431         for (i = 3; i < rowstride; i+=4) {
432                 if (row[i] < 0xfe) {
433                         return FALSE;
434                 }
435         }
436
437         return TRUE;
438 }
439
440 static GdkPixbuf *
441 avatar_pixbuf_from_loader (GdkPixbufLoader *loader)
442 {
443         GdkPixbuf *pixbuf;
444
445         pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
446         if (!gdk_pixbuf_get_has_alpha (pixbuf)) {
447                 GdkPixbuf *rounded_pixbuf;
448
449                 rounded_pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8,
450                                                  gdk_pixbuf_get_width (pixbuf),
451                                                  gdk_pixbuf_get_height (pixbuf));
452                 gdk_pixbuf_copy_area (pixbuf, 0, 0,
453                                       gdk_pixbuf_get_width (pixbuf),
454                                       gdk_pixbuf_get_height (pixbuf),
455                                       rounded_pixbuf,
456                                       0, 0);
457                 pixbuf = rounded_pixbuf;
458         } else {
459                 g_object_ref (pixbuf);
460         }
461
462         if (empathy_gdk_pixbuf_is_opaque (pixbuf)) {
463                 empathy_avatar_pixbuf_roundify (pixbuf);
464         }
465
466         return pixbuf;
467 }
468
469 GdkPixbuf *
470 empathy_pixbuf_from_avatar_scaled (EmpathyAvatar *avatar,
471                                   gint          width,
472                                   gint          height)
473 {
474         GdkPixbuf        *pixbuf;
475         GdkPixbufLoader  *loader;
476         struct SizeData   data;
477         GError           *error = NULL;
478
479         if (!avatar) {
480                 return NULL;
481         }
482
483         data.width = width;
484         data.height = height;
485         data.preserve_aspect_ratio = TRUE;
486
487         loader = gdk_pixbuf_loader_new ();
488
489         g_signal_connect (loader, "size-prepared",
490                           G_CALLBACK (pixbuf_from_avatar_size_prepared_cb),
491                           &data);
492
493         if (!gdk_pixbuf_loader_write (loader, avatar->data, avatar->len, &error)) {
494                 g_warning ("Couldn't write avatar image:%p with "
495                            "length:%" G_GSIZE_FORMAT " to pixbuf loader: %s",
496                            avatar->data, avatar->len, error->message);
497                 g_error_free (error);
498                 return NULL;
499         }
500
501         gdk_pixbuf_loader_close (loader, NULL);
502         pixbuf = avatar_pixbuf_from_loader (loader);
503
504         g_object_unref (loader);
505
506         return pixbuf;
507 }
508
509 GdkPixbuf *
510 empathy_pixbuf_avatar_from_contact_scaled (EmpathyContact *contact,
511                                           gint           width,
512                                           gint           height)
513 {
514         EmpathyAvatar *avatar;
515
516         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
517
518         avatar = empathy_contact_get_avatar (contact);
519
520         return empathy_pixbuf_from_avatar_scaled (avatar, width, height);
521 }
522
523 typedef struct {
524         FolksIndividual *individual;
525         GSimpleAsyncResult *result;
526         guint width;
527         guint height;
528 } PixbufAvatarFromIndividualClosure;
529
530 static PixbufAvatarFromIndividualClosure *
531 pixbuf_avatar_from_individual_closure_new (FolksIndividual    *individual,
532                                            GSimpleAsyncResult *result,
533                                            gint                width,
534                                            gint                height)
535 {
536         PixbufAvatarFromIndividualClosure *closure;
537
538         g_return_val_if_fail (FOLKS_IS_INDIVIDUAL (individual), NULL);
539         g_return_val_if_fail (G_IS_ASYNC_RESULT (result), NULL);
540
541         closure = g_new0 (PixbufAvatarFromIndividualClosure, 1);
542         closure->individual = g_object_ref (individual);
543         closure->result = g_object_ref (result);
544         closure->width = width;
545         closure->height = height;
546
547         return closure;
548 }
549
550 static void
551 pixbuf_avatar_from_individual_closure_free (
552                 PixbufAvatarFromIndividualClosure *closure)
553 {
554         g_object_unref (closure->individual);
555         g_object_unref (closure->result);
556         g_free (closure);
557 }
558
559 static void
560 avatar_file_load_contents_cb (GObject      *object,
561                               GAsyncResult *result,
562                               gpointer      user_data)
563 {
564         GFile *file = G_FILE (object);
565         PixbufAvatarFromIndividualClosure *closure = user_data;
566         char *data;
567         gsize data_size;
568         struct SizeData size_data;
569         GError *error = NULL;
570         GdkPixbufLoader *loader = NULL;
571
572         if (!g_file_load_contents_finish (file, result, &data, &data_size,
573                                 NULL, &error)) {
574                 DEBUG ("failed to load avatar from file: %s",
575                                 error->message);
576                 g_simple_async_result_set_from_error (closure->result, error);
577                 goto out;
578         }
579
580         size_data.width = closure->width;
581         size_data.height = closure->height;
582         size_data.preserve_aspect_ratio = TRUE;
583
584         loader = gdk_pixbuf_loader_new ();
585
586         g_signal_connect (loader, "size-prepared",
587                           G_CALLBACK (pixbuf_from_avatar_size_prepared_cb),
588                           &size_data);
589
590         if (!gdk_pixbuf_loader_write (loader, (guchar *) data, data_size,
591                                 &error)) {
592                 DEBUG ("Failed to write to pixbuf loader: %s",
593                         error ? error->message : "No error given");
594                 g_simple_async_result_set_from_error (closure->result, error);
595                 goto out;
596         }
597         if (!gdk_pixbuf_loader_close (loader, &error)) {
598                 DEBUG ("Failed to close pixbuf loader: %s",
599                         error ? error->message : "No error given");
600                 g_simple_async_result_set_from_error (closure->result, error);
601                 goto out;
602         }
603
604         g_simple_async_result_set_op_res_gpointer (closure->result,
605                         avatar_pixbuf_from_loader (loader), NULL);
606
607 out:
608         g_simple_async_result_complete (closure->result);
609
610         g_clear_error (&error);
611         g_free (data);
612         tp_clear_object (&loader);
613         pixbuf_avatar_from_individual_closure_free (closure);
614 }
615
616 void
617 empathy_pixbuf_avatar_from_individual_scaled_async (
618                 FolksIndividual     *individual,
619                 GAsyncReadyCallback  callback,
620                 gint                 width,
621                 gint                 height,
622                 gpointer             user_data)
623 {
624         GFile *avatar_file;
625         GSimpleAsyncResult *result;
626         PixbufAvatarFromIndividualClosure *closure;
627
628         result = g_simple_async_result_new (G_OBJECT (individual),
629                         callback, user_data,
630                         empathy_pixbuf_avatar_from_individual_scaled_finish);
631
632         avatar_file = folks_avatar_get_avatar (FOLKS_AVATAR (individual));
633         if (avatar_file == NULL)
634                 goto out;
635
636         closure = pixbuf_avatar_from_individual_closure_new (individual, result,
637                                                              width, height);
638         if (closure == NULL)
639                 goto out;
640
641         g_file_load_contents_async (avatar_file, NULL,
642                         avatar_file_load_contents_cb, closure);
643
644         g_object_unref (result);
645
646         return;
647
648 out:
649         g_simple_async_result_set_op_res_gpointer (result, NULL, NULL);
650         g_simple_async_result_complete (result);
651         g_object_unref (result);
652 }
653
654 GdkPixbuf *
655 empathy_pixbuf_avatar_from_individual_scaled_finish (
656                 FolksIndividual *individual,
657                 GAsyncResult *result,
658                 GError **error)
659 {
660         GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
661         gboolean result_valid;
662
663         g_return_val_if_fail (FOLKS_IS_INDIVIDUAL (individual), NULL);
664         g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), NULL);
665
666         if (g_simple_async_result_propagate_error (simple, error))
667                 return NULL;
668
669         result_valid = g_simple_async_result_is_valid (result,
670                         G_OBJECT (individual),
671                         empathy_pixbuf_avatar_from_individual_scaled_finish);
672         g_return_val_if_fail (result_valid, NULL);
673
674         return g_simple_async_result_get_op_res_gpointer (simple);
675 }
676
677 GdkPixbuf *
678 empathy_pixbuf_contact_status_icon (EmpathyContact *contact,
679                                    gboolean       show_protocol)
680 {
681         const gchar *icon_name;
682
683         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
684
685         icon_name = empathy_icon_name_for_contact (contact);
686
687         if (icon_name == NULL) {
688                 return NULL;
689         }
690         return empathy_pixbuf_contact_status_icon_with_icon_name (contact,
691             icon_name,
692             show_protocol);
693 }
694
695 GdkPixbuf *
696 empathy_pixbuf_contact_status_icon_with_icon_name (EmpathyContact *contact,
697                                           const gchar    *icon_name,
698                                           gboolean       show_protocol)
699 {
700         GdkPixbuf *pix_status;
701         GdkPixbuf *pix_protocol;
702         gchar     *icon_filename;
703         gint       height, width;
704         gint       numerator, denominator;
705
706         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact) ||
707                         (show_protocol == FALSE), NULL);
708         g_return_val_if_fail (icon_name != NULL, NULL);
709
710         numerator = 3;
711         denominator = 4;
712
713         icon_filename = empathy_filename_from_icon_name (icon_name,
714                                                          GTK_ICON_SIZE_MENU);
715         if (icon_filename == NULL) {
716                 DEBUG ("icon name: %s could not be found\n", icon_name);
717                 return NULL;
718         }
719
720         pix_status = gdk_pixbuf_new_from_file (icon_filename, NULL);
721
722         if (pix_status == NULL) {
723                 DEBUG ("Could not open icon %s\n", icon_filename);
724                 g_free (icon_filename);
725                 return NULL;
726         }
727
728         g_free (icon_filename);
729
730         if (!show_protocol)
731                 return pix_status;
732
733         height = gdk_pixbuf_get_height (pix_status);
734         width = gdk_pixbuf_get_width (pix_status);
735
736         pix_protocol = empathy_pixbuf_protocol_from_contact_scaled (contact,
737                                                                     width * numerator / denominator,
738                                                                     height * numerator / denominator);
739
740         if (pix_protocol == NULL) {
741                 return pix_status;
742         }
743         gdk_pixbuf_composite (pix_protocol, pix_status,
744             0, height - height * numerator / denominator,
745             width * numerator / denominator, height * numerator / denominator,
746             0, height - height * numerator / denominator,
747             1, 1,
748             GDK_INTERP_BILINEAR, 255);
749
750         g_object_unref (pix_protocol);
751
752         return pix_status;
753 }
754
755 GdkPixbuf *
756 empathy_pixbuf_protocol_from_contact_scaled (EmpathyContact *contact,
757                                           gint           width,
758                                           gint           height)
759 {
760         TpAccount *account;
761         gchar     *filename;
762         GdkPixbuf *pixbuf = NULL;
763
764         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
765
766         account = empathy_contact_get_account (contact);
767         filename = empathy_filename_from_icon_name (tp_account_get_icon_name (account),
768                                                     GTK_ICON_SIZE_MENU);
769         if (filename != NULL) {
770                 pixbuf = gdk_pixbuf_new_from_file_at_size (filename, width, height, NULL);
771                 g_free (filename);
772         }
773
774         return pixbuf;
775 }
776
777 GdkPixbuf *
778 empathy_pixbuf_scale_down_if_necessary (GdkPixbuf *pixbuf, gint max_size)
779 {
780         gint      width, height;
781         gdouble   factor;
782
783         width = gdk_pixbuf_get_width (pixbuf);
784         height = gdk_pixbuf_get_height (pixbuf);
785
786         if (width > 0 && (width > max_size || height > max_size)) {
787                 factor = (gdouble) max_size / MAX (width, height);
788
789                 width = width * factor;
790                 height = height * factor;
791
792                 return gdk_pixbuf_scale_simple (pixbuf,
793                                                 width, height,
794                                                 GDK_INTERP_HYPER);
795         }
796
797         return g_object_ref (pixbuf);
798 }
799
800 GdkPixbuf *
801 empathy_pixbuf_from_icon_name_sized (const gchar *icon_name,
802                                      gint size)
803 {
804         GtkIconTheme *theme;
805         GdkPixbuf *pixbuf;
806         GError *error = NULL;
807
808         if (!icon_name) {
809                 return NULL;
810         }
811
812         theme = gtk_icon_theme_get_default ();
813
814         pixbuf = gtk_icon_theme_load_icon (theme,
815                                            icon_name,
816                                            size,
817                                            0,
818                                            &error);
819         if (error) {
820                 DEBUG ("Error loading icon: %s", error->message);
821                 g_clear_error (&error);
822         }
823
824         return pixbuf;
825 }
826
827 GdkPixbuf *
828 empathy_pixbuf_from_icon_name (const gchar *icon_name,
829                                GtkIconSize  icon_size)
830 {
831         gint  w, h;
832         gint  size = 48;
833
834         if (!icon_name) {
835                 return NULL;
836         }
837
838         if (gtk_icon_size_lookup (icon_size, &w, &h)) {
839                 size = (w + h) / 2;
840         }
841
842         return empathy_pixbuf_from_icon_name_sized (icon_name, size);
843 }
844
845 gchar *
846 empathy_filename_from_icon_name (const gchar *icon_name,
847                                  GtkIconSize  icon_size)
848 {
849         GtkIconTheme *icon_theme;
850         GtkIconInfo  *icon_info;
851         gint          w, h;
852         gint          size = 48;
853         gchar        *ret;
854
855         icon_theme = gtk_icon_theme_get_default ();
856
857         if (gtk_icon_size_lookup (icon_size, &w, &h)) {
858                 size = (w + h) / 2;
859         }
860
861         icon_info = gtk_icon_theme_lookup_icon (icon_theme, icon_name, size, 0);
862         ret = g_strdup (gtk_icon_info_get_filename (icon_info));
863         gtk_icon_info_free (icon_info);
864
865         return ret;
866 }
867
868 /* Stolen from GtkSourceView, hence the weird intendation. Please keep it like
869  * that to make it easier to apply changes from the original code.
870  */
871 #define GTK_TEXT_UNKNOWN_CHAR 0xFFFC
872
873 /* this function acts like g_utf8_offset_to_pointer() except that if it finds a
874  * decomposable character it consumes the decomposition length from the given
875  * offset.  So it's useful when the offset was calculated for the normalized
876  * version of str, but we need a pointer to str itself. */
877 static const gchar *
878 pointer_from_offset_skipping_decomp (const gchar *str, gint offset)
879 {
880         gchar *casefold, *normal;
881         const gchar *p, *q;
882
883         p = str;
884         while (offset > 0)
885         {
886                 q = g_utf8_next_char (p);
887                 casefold = g_utf8_casefold (p, q - p);
888                 normal = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
889                 offset -= g_utf8_strlen (normal, -1);
890                 g_free (casefold);
891                 g_free (normal);
892                 p = q;
893         }
894         return p;
895 }
896
897 static const gchar *
898 g_utf8_strcasestr (const gchar *haystack, const gchar *needle)
899 {
900         gsize needle_len;
901         gsize haystack_len;
902         const gchar *ret = NULL;
903         gchar *p;
904         gchar *casefold;
905         gchar *caseless_haystack;
906         gint i;
907
908         g_return_val_if_fail (haystack != NULL, NULL);
909         g_return_val_if_fail (needle != NULL, NULL);
910
911         casefold = g_utf8_casefold (haystack, -1);
912         caseless_haystack = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
913         g_free (casefold);
914
915         needle_len = g_utf8_strlen (needle, -1);
916         haystack_len = g_utf8_strlen (caseless_haystack, -1);
917
918         if (needle_len == 0)
919         {
920                 ret = (gchar *) haystack;
921                 goto finally_1;
922         }
923
924         if (haystack_len < needle_len)
925         {
926                 ret = NULL;
927                 goto finally_1;
928         }
929
930         p = (gchar *) caseless_haystack;
931         needle_len = strlen (needle);
932         i = 0;
933
934         while (*p)
935         {
936                 if ((strncmp (p, needle, needle_len) == 0))
937                 {
938                         ret = pointer_from_offset_skipping_decomp (haystack, i);
939                         goto finally_1;
940                 }
941
942                 p = g_utf8_next_char (p);
943                 i++;
944         }
945
946 finally_1:
947         g_free (caseless_haystack);
948
949         return ret;
950 }
951
952 static gboolean
953 g_utf8_caselessnmatch (const char *s1, const char *s2,
954                        gssize n1, gssize n2)
955 {
956         gchar *casefold;
957         gchar *normalized_s1;
958         gchar *normalized_s2;
959         gint len_s1;
960         gint len_s2;
961         gboolean ret = FALSE;
962
963         g_return_val_if_fail (s1 != NULL, FALSE);
964         g_return_val_if_fail (s2 != NULL, FALSE);
965         g_return_val_if_fail (n1 > 0, FALSE);
966         g_return_val_if_fail (n2 > 0, FALSE);
967
968         casefold = g_utf8_casefold (s1, n1);
969         normalized_s1 = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
970         g_free (casefold);
971
972         casefold = g_utf8_casefold (s2, n2);
973         normalized_s2 = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
974         g_free (casefold);
975
976         len_s1 = strlen (normalized_s1);
977         len_s2 = strlen (normalized_s2);
978
979         if (len_s1 < len_s2)
980                 goto finally_2;
981
982         ret = (strncmp (normalized_s1, normalized_s2, len_s2) == 0);
983
984 finally_2:
985         g_free (normalized_s1);
986         g_free (normalized_s2);
987
988         return ret;
989 }
990
991 static void
992 forward_chars_with_skipping (GtkTextIter *iter,
993                              gint         count,
994                              gboolean     skip_invisible,
995                              gboolean     skip_nontext,
996                              gboolean     skip_decomp)
997 {
998         gint i;
999
1000         g_return_if_fail (count >= 0);
1001
1002         i = count;
1003
1004         while (i > 0)
1005         {
1006                 gboolean ignored = FALSE;
1007
1008                 /* minimal workaround to avoid the infinite loop of bug #168247.
1009                  * It doesn't fix the problemjust the symptom...
1010                  */
1011                 if (gtk_text_iter_is_end (iter))
1012                         return;
1013
1014                 if (skip_nontext && gtk_text_iter_get_char (iter) == GTK_TEXT_UNKNOWN_CHAR)
1015                         ignored = TRUE;
1016
1017                 if (!ignored && skip_invisible &&
1018                     /* _gtk_text_btree_char_is_invisible (iter)*/ FALSE)
1019                         ignored = TRUE;
1020
1021                 if (!ignored && skip_decomp)
1022                 {
1023                         /* being UTF8 correct sucks; this accounts for extra
1024                            offsets coming from canonical decompositions of
1025                            UTF8 characters (e.g. accented characters) which
1026                            g_utf8_normalize () performs */
1027                         gchar *normal;
1028                         gchar buffer[6];
1029                         gint buffer_len;
1030
1031                         buffer_len = g_unichar_to_utf8 (gtk_text_iter_get_char (iter), buffer);
1032                         normal = g_utf8_normalize (buffer, buffer_len, G_NORMALIZE_NFD);
1033                         i -= (g_utf8_strlen (normal, -1) - 1);
1034                         g_free (normal);
1035                 }
1036
1037                 gtk_text_iter_forward_char (iter);
1038
1039                 if (!ignored)
1040                         --i;
1041         }
1042 }
1043
1044 static gboolean
1045 lines_match (const GtkTextIter *start,
1046              const gchar      **lines,
1047              gboolean           visible_only,
1048              gboolean           slice,
1049              GtkTextIter       *match_start,
1050              GtkTextIter       *match_end)
1051 {
1052         GtkTextIter next;
1053         gchar *line_text;
1054         const gchar *found;
1055         gint offset;
1056
1057         if (*lines == NULL || **lines == '\0')
1058         {
1059                 if (match_start)
1060                         *match_start = *start;
1061                 if (match_end)
1062                         *match_end = *start;
1063                 return TRUE;
1064         }
1065
1066         next = *start;
1067         gtk_text_iter_forward_line (&next);
1068
1069         /* No more text in buffer, but *lines is nonempty */
1070         if (gtk_text_iter_equal (start, &next))
1071                 return FALSE;
1072
1073         if (slice)
1074         {
1075                 if (visible_only)
1076                         line_text = gtk_text_iter_get_visible_slice (start, &next);
1077                 else
1078                         line_text = gtk_text_iter_get_slice (start, &next);
1079         }
1080         else
1081         {
1082                 if (visible_only)
1083                         line_text = gtk_text_iter_get_visible_text (start, &next);
1084                 else
1085                         line_text = gtk_text_iter_get_text (start, &next);
1086         }
1087
1088         if (match_start) /* if this is the first line we're matching */
1089         {
1090                 found = g_utf8_strcasestr (line_text, *lines);
1091         }
1092         else
1093         {
1094                 /* If it's not the first line, we have to match from the
1095                  * start of the line.
1096                  */
1097                 if (g_utf8_caselessnmatch (line_text, *lines, strlen (line_text),
1098                                            strlen (*lines)))
1099                         found = line_text;
1100                 else
1101                         found = NULL;
1102         }
1103
1104         if (found == NULL)
1105         {
1106                 g_free (line_text);
1107                 return FALSE;
1108         }
1109
1110         /* Get offset to start of search string */
1111         offset = g_utf8_strlen (line_text, found - line_text);
1112
1113         next = *start;
1114
1115         /* If match start needs to be returned, set it to the
1116          * start of the search string.
1117          */
1118         forward_chars_with_skipping (&next, offset, visible_only, !slice, FALSE);
1119         if (match_start)
1120         {
1121                 *match_start = next;
1122         }
1123
1124         /* Go to end of search string */
1125         forward_chars_with_skipping (&next, g_utf8_strlen (*lines, -1), visible_only, !slice, TRUE);
1126
1127         g_free (line_text);
1128
1129         ++lines;
1130
1131         if (match_end)
1132                 *match_end = next;
1133
1134         /* pass NULL for match_start, since we don't need to find the
1135          * start again.
1136          */
1137         return lines_match (&next, lines, visible_only, slice, NULL, match_end);
1138 }
1139
1140 /* strsplit () that retains the delimiter as part of the string. */
1141 static gchar **
1142 strbreakup (const char *string,
1143             const char *delimiter,
1144             gint        max_tokens)
1145 {
1146         GSList *string_list = NULL, *slist;
1147         gchar **str_array, *s, *casefold, *new_string;
1148         guint i, n = 1;
1149
1150         g_return_val_if_fail (string != NULL, NULL);
1151         g_return_val_if_fail (delimiter != NULL, NULL);
1152
1153         if (max_tokens < 1)
1154                 max_tokens = G_MAXINT;
1155
1156         s = strstr (string, delimiter);
1157         if (s)
1158         {
1159                 guint delimiter_len = strlen (delimiter);
1160
1161                 do
1162                 {
1163                         guint len;
1164
1165                         len = s - string + delimiter_len;
1166                         new_string = g_new (gchar, len + 1);
1167                         strncpy (new_string, string, len);
1168                         new_string[len] = 0;
1169                         casefold = g_utf8_casefold (new_string, -1);
1170                         g_free (new_string);
1171                         new_string = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1172                         g_free (casefold);
1173                         string_list = g_slist_prepend (string_list, new_string);
1174                         n++;
1175                         string = s + delimiter_len;
1176                         s = strstr (string, delimiter);
1177                 } while (--max_tokens && s);
1178         }
1179
1180         if (*string)
1181         {
1182                 n++;
1183                 casefold = g_utf8_casefold (string, -1);
1184                 new_string = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1185                 g_free (casefold);
1186                 string_list = g_slist_prepend (string_list, new_string);
1187         }
1188
1189         str_array = g_new (gchar*, n);
1190
1191         i = n - 1;
1192
1193         str_array[i--] = NULL;
1194         for (slist = string_list; slist; slist = slist->next)
1195                 str_array[i--] = slist->data;
1196
1197         g_slist_free (string_list);
1198
1199         return str_array;
1200 }
1201
1202 gboolean
1203 empathy_text_iter_forward_search (const GtkTextIter   *iter,
1204                                  const gchar         *str,
1205                                  GtkTextIter         *match_start,
1206                                  GtkTextIter         *match_end,
1207                                  const GtkTextIter   *limit)
1208 {
1209         gchar **lines = NULL;
1210         GtkTextIter match;
1211         gboolean retval = FALSE;
1212         GtkTextIter search;
1213         gboolean visible_only;
1214         gboolean slice;
1215
1216         g_return_val_if_fail (iter != NULL, FALSE);
1217         g_return_val_if_fail (str != NULL, FALSE);
1218
1219         if (limit && gtk_text_iter_compare (iter, limit) >= 0)
1220                 return FALSE;
1221
1222         if (*str == '\0') {
1223                 /* If we can move one char, return the empty string there */
1224                 match = *iter;
1225
1226                 if (gtk_text_iter_forward_char (&match)) {
1227                         if (limit && gtk_text_iter_equal (&match, limit)) {
1228                                 return FALSE;
1229                         }
1230
1231                         if (match_start) {
1232                                 *match_start = match;
1233                         }
1234                         if (match_end) {
1235                                 *match_end = match;
1236                         }
1237                         return TRUE;
1238                 } else {
1239                         return FALSE;
1240                 }
1241         }
1242
1243         visible_only = TRUE;
1244         slice = FALSE;
1245
1246         /* locate all lines */
1247         lines = strbreakup (str, "\n", -1);
1248
1249         search = *iter;
1250
1251         do {
1252                 /* This loop has an inefficient worst-case, where
1253                  * gtk_text_iter_get_text () is called repeatedly on
1254                  * a single line.
1255                  */
1256                 GtkTextIter end;
1257
1258                 if (limit && gtk_text_iter_compare (&search, limit) >= 0) {
1259                         break;
1260                 }
1261
1262                 if (lines_match (&search, (const gchar**)lines,
1263                                  visible_only, slice, &match, &end)) {
1264                         if (limit == NULL ||
1265                             (limit && gtk_text_iter_compare (&end, limit) <= 0)) {
1266                                 retval = TRUE;
1267
1268                                 if (match_start) {
1269                                         *match_start = match;
1270                                 }
1271                                 if (match_end) {
1272                                         *match_end = end;
1273                                 }
1274                         }
1275                         break;
1276                 }
1277         } while (gtk_text_iter_forward_line (&search));
1278
1279         g_strfreev ((gchar **) lines);
1280
1281         return retval;
1282 }
1283
1284 static const gchar *
1285 g_utf8_strrcasestr (const gchar *haystack, const gchar *needle)
1286 {
1287         gsize needle_len;
1288         gsize haystack_len;
1289         const gchar *ret = NULL;
1290         gchar *p;
1291         gchar *casefold;
1292         gchar *caseless_haystack;
1293         gint i;
1294
1295         g_return_val_if_fail (haystack != NULL, NULL);
1296         g_return_val_if_fail (needle != NULL, NULL);
1297
1298         casefold = g_utf8_casefold (haystack, -1);
1299         caseless_haystack = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1300         g_free (casefold);
1301
1302         needle_len = g_utf8_strlen (needle, -1);
1303         haystack_len = g_utf8_strlen (caseless_haystack, -1);
1304
1305         if (needle_len == 0)
1306         {
1307                 ret = (gchar *) haystack;
1308                 goto finally_1;
1309         }
1310
1311         if (haystack_len < needle_len)
1312         {
1313                 ret = NULL;
1314                 goto finally_1;
1315         }
1316
1317         i = haystack_len - needle_len;
1318         p = g_utf8_offset_to_pointer (caseless_haystack, i);
1319         needle_len = strlen (needle);
1320
1321         while (p >= caseless_haystack)
1322         {
1323                 if (strncmp (p, needle, needle_len) == 0)
1324                 {
1325                         ret = pointer_from_offset_skipping_decomp (haystack, i);
1326                         goto finally_1;
1327                 }
1328
1329                 p = g_utf8_prev_char (p);
1330                 i--;
1331         }
1332
1333 finally_1:
1334         g_free (caseless_haystack);
1335
1336         return ret;
1337 }
1338
1339 static gboolean
1340 backward_lines_match (const GtkTextIter *start,
1341                       const gchar      **lines,
1342                       gboolean           visible_only,
1343                       gboolean           slice,
1344                       GtkTextIter       *match_start,
1345                       GtkTextIter       *match_end)
1346 {
1347         GtkTextIter line, next;
1348         gchar *line_text;
1349         const gchar *found;
1350         gint offset;
1351
1352         if (*lines == NULL || **lines == '\0')
1353         {
1354                 if (match_start)
1355                         *match_start = *start;
1356                 if (match_end)
1357                         *match_end = *start;
1358                 return TRUE;
1359         }
1360
1361         line = next = *start;
1362         if (gtk_text_iter_get_line_offset (&next) == 0)
1363         {
1364                 if (!gtk_text_iter_backward_line (&next))
1365                         return FALSE;
1366         }
1367         else
1368                 gtk_text_iter_set_line_offset (&next, 0);
1369
1370         if (slice)
1371         {
1372                 if (visible_only)
1373                         line_text = gtk_text_iter_get_visible_slice (&next, &line);
1374                 else
1375                         line_text = gtk_text_iter_get_slice (&next, &line);
1376         }
1377         else
1378         {
1379                 if (visible_only)
1380                         line_text = gtk_text_iter_get_visible_text (&next, &line);
1381                 else
1382                         line_text = gtk_text_iter_get_text (&next, &line);
1383         }
1384
1385         if (match_start) /* if this is the first line we're matching */
1386         {
1387                 found = g_utf8_strrcasestr (line_text, *lines);
1388         }
1389         else
1390         {
1391                 /* If it's not the first line, we have to match from the
1392                  * start of the line.
1393                  */
1394                 if (g_utf8_caselessnmatch (line_text, *lines, strlen (line_text),
1395                                            strlen (*lines)))
1396                         found = line_text;
1397                 else
1398                         found = NULL;
1399         }
1400
1401         if (found == NULL)
1402         {
1403                 g_free (line_text);
1404                 return FALSE;
1405         }
1406
1407         /* Get offset to start of search string */
1408         offset = g_utf8_strlen (line_text, found - line_text);
1409
1410         forward_chars_with_skipping (&next, offset, visible_only, !slice, FALSE);
1411
1412         /* If match start needs to be returned, set it to the
1413          * start of the search string.
1414          */
1415         if (match_start)
1416         {
1417                 *match_start = next;
1418         }
1419
1420         /* Go to end of search string */
1421         forward_chars_with_skipping (&next, g_utf8_strlen (*lines, -1), visible_only, !slice, TRUE);
1422
1423         g_free (line_text);
1424
1425         ++lines;
1426
1427         if (match_end)
1428                 *match_end = next;
1429
1430         /* try to match the rest of the lines forward, passing NULL
1431          * for match_start so lines_match will try to match the entire
1432          * line */
1433         return lines_match (&next, lines, visible_only,
1434                             slice, NULL, match_end);
1435 }
1436
1437 gboolean
1438 empathy_text_iter_backward_search (const GtkTextIter   *iter,
1439                                   const gchar         *str,
1440                                   GtkTextIter         *match_start,
1441                                   GtkTextIter         *match_end,
1442                                   const GtkTextIter   *limit)
1443 {
1444         gchar **lines = NULL;
1445         GtkTextIter match;
1446         gboolean retval = FALSE;
1447         GtkTextIter search;
1448         gboolean visible_only;
1449         gboolean slice;
1450
1451         g_return_val_if_fail (iter != NULL, FALSE);
1452         g_return_val_if_fail (str != NULL, FALSE);
1453
1454         if (limit && gtk_text_iter_compare (iter, limit) <= 0)
1455                 return FALSE;
1456
1457         if (*str == '\0')
1458         {
1459                 /* If we can move one char, return the empty string there */
1460                 match = *iter;
1461
1462                 if (gtk_text_iter_backward_char (&match))
1463                 {
1464                         if (limit && gtk_text_iter_equal (&match, limit))
1465                                 return FALSE;
1466
1467                         if (match_start)
1468                                 *match_start = match;
1469                         if (match_end)
1470                                 *match_end = match;
1471                         return TRUE;
1472                 }
1473                 else
1474                 {
1475                         return FALSE;
1476                 }
1477         }
1478
1479         visible_only = TRUE;
1480         slice = TRUE;
1481
1482         /* locate all lines */
1483         lines = strbreakup (str, "\n", -1);
1484
1485         search = *iter;
1486
1487         while (TRUE)
1488         {
1489                 /* This loop has an inefficient worst-case, where
1490                  * gtk_text_iter_get_text () is called repeatedly on
1491                  * a single line.
1492                  */
1493                 GtkTextIter end;
1494
1495                 if (limit && gtk_text_iter_compare (&search, limit) <= 0)
1496                         break;
1497
1498                 if (backward_lines_match (&search, (const gchar**)lines,
1499                                           visible_only, slice, &match, &end))
1500                 {
1501                         if (limit == NULL || (limit &&
1502                                               gtk_text_iter_compare (&end, limit) > 0))
1503                         {
1504                                 retval = TRUE;
1505
1506                                 if (match_start)
1507                                         *match_start = match;
1508                                 if (match_end)
1509                                         *match_end = end;
1510                         }
1511                         break;
1512                 }
1513
1514                 if (gtk_text_iter_get_line_offset (&search) == 0)
1515                 {
1516                         if (!gtk_text_iter_backward_line (&search))
1517                                 break;
1518                 }
1519                 else
1520                 {
1521                         gtk_text_iter_set_line_offset (&search, 0);
1522                 }
1523         }
1524
1525         g_strfreev ((gchar **) lines);
1526
1527         return retval;
1528 }
1529
1530 gboolean
1531 empathy_window_get_is_visible (GtkWindow *window)
1532 {
1533         GdkWindowState  state;
1534         GdkWindow      *gdk_window;
1535
1536         g_return_val_if_fail (GTK_IS_WINDOW (window), FALSE);
1537
1538         gdk_window = gtk_widget_get_window (GTK_WIDGET (window));
1539         if (!gdk_window) {
1540                 return FALSE;
1541         }
1542
1543         state = gdk_window_get_state (gdk_window);
1544         if (state & (GDK_WINDOW_STATE_WITHDRAWN | GDK_WINDOW_STATE_ICONIFIED)) {
1545                 return FALSE;
1546         }
1547
1548         return TRUE;
1549 }
1550
1551 void
1552 empathy_window_iconify (GtkWindow *window, GtkStatusIcon *status_icon)
1553 {
1554         GdkRectangle  icon_location;
1555         gulong        data[4];
1556         Display      *dpy;
1557         GdkWindow    *gdk_window;
1558
1559         gtk_status_icon_get_geometry (status_icon, NULL, &icon_location, NULL);
1560         gdk_window = gtk_widget_get_window (GTK_WIDGET (window));
1561         dpy = gdk_x11_drawable_get_xdisplay (gdk_window);
1562
1563         data[0] = icon_location.x;
1564         data[1] = icon_location.y;
1565         data[2] = icon_location.width;
1566         data[3] = icon_location.height;
1567
1568         XChangeProperty (dpy,
1569                          GDK_WINDOW_XID (gdk_window),
1570                          gdk_x11_get_xatom_by_name_for_display (
1571                                 gdk_drawable_get_display (gdk_window),
1572                          "_NET_WM_ICON_GEOMETRY"),
1573                          XA_CARDINAL, 32, PropModeReplace,
1574                          (guchar *)&data, 4);
1575
1576         gtk_window_set_skip_taskbar_hint (window, TRUE);
1577         gtk_window_iconify (window);
1578 }
1579
1580 /* Takes care of moving the window to the current workspace. */
1581 void
1582 empathy_window_present_with_time (GtkWindow *window,
1583                         guint32 timestamp)
1584 {
1585         GdkWindow *gdk_window;
1586
1587         g_return_if_fail (GTK_IS_WINDOW (window));
1588
1589         /* Move the window to the current workspace before trying to show it.
1590          * This is the behaviour people expect when clicking on the statusbar icon. */
1591         gdk_window = gtk_widget_get_window (GTK_WIDGET (window));
1592         if (gdk_window) {
1593                 gint x, y;
1594                 gint w, h;
1595
1596                 /* Has no effect if the WM has viewports, like compiz */
1597                 gdk_x11_window_move_to_current_desktop (gdk_window);
1598
1599                 /* If window is still off-screen, hide it to force it to
1600                  * reposition on the current workspace. */
1601                 gtk_window_get_position (window, &x, &y);
1602                 gtk_window_get_size (window, &w, &h);
1603                 if (!EMPATHY_RECT_IS_ON_SCREEN (x, y, w, h))
1604                         gtk_widget_hide (GTK_WIDGET (window));
1605         }
1606
1607         gtk_window_present_with_time (window, timestamp);
1608         gtk_window_set_skip_taskbar_hint (window, FALSE);
1609         gtk_window_deiconify (window);
1610 }
1611
1612 void
1613 empathy_window_present (GtkWindow *window)
1614 {
1615   empathy_window_present_with_time (window, GDK_CURRENT_TIME);
1616 }
1617
1618 GtkWindow *
1619 empathy_get_toplevel_window (GtkWidget *widget)
1620 {
1621         GtkWidget *toplevel;
1622
1623         g_return_val_if_fail (GTK_IS_WIDGET (widget), NULL);
1624
1625         toplevel = gtk_widget_get_toplevel (widget);
1626         if (GTK_IS_WINDOW (toplevel) &&
1627             gtk_widget_is_toplevel (toplevel)) {
1628                 return GTK_WINDOW (toplevel);
1629         }
1630
1631         return NULL;
1632 }
1633
1634 /** empathy_make_absolute_url_len:
1635  * @url: an url
1636  * @len: a length
1637  *
1638  * Same as #empathy_make_absolute_url but for a limited string length
1639  */
1640 gchar *
1641 empathy_make_absolute_url_len (const gchar *url,
1642                                guint len)
1643 {
1644         g_return_val_if_fail (url != NULL, NULL);
1645
1646         if (g_str_has_prefix (url, "ghelp:") ||
1647             g_str_has_prefix (url, "mailto:") ||
1648             strstr (url, ":/")) {
1649                 return g_strndup (url, len);
1650         }
1651
1652         if (strstr (url, "@")) {
1653                 return g_strdup_printf ("mailto:%.*s", len, url);
1654         }
1655
1656         return g_strdup_printf ("http://%.*s", len, url);
1657 }
1658
1659 /** empathy_make_absolute_url:
1660  * @url: an url
1661  *
1662  * The URL opening code can't handle schemeless strings, so we try to be
1663  * smart and add http if there is no scheme or doesn't look like a mail
1664  * address. This should work in most cases, and let us click on strings
1665  * like "www.gnome.org".
1666  *
1667  * Returns: a newly allocated url with proper mailto: or http:// prefix, use
1668  * g_free when your are done with it
1669  */
1670 gchar *
1671 empathy_make_absolute_url (const gchar *url)
1672 {
1673         return empathy_make_absolute_url_len (url, strlen (url));
1674 }
1675
1676 void
1677 empathy_url_show (GtkWidget *parent,
1678                   const char *url)
1679 {
1680         gchar  *real_url;
1681         GError *error = NULL;
1682
1683         g_return_if_fail (parent == NULL || GTK_IS_WIDGET (parent));
1684         g_return_if_fail (url != NULL);
1685
1686         real_url = empathy_make_absolute_url (url);
1687
1688         gtk_show_uri (parent ? gtk_widget_get_screen (parent) : NULL, real_url,
1689                       gtk_get_current_event_time (), &error);
1690
1691         if (error) {
1692                 GtkWidget *dialog;
1693
1694                 dialog = gtk_message_dialog_new (NULL, 0,
1695                                                  GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,
1696                                                  _("Unable to open URI"));
1697                 gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
1698                                                           "%s", error->message);
1699
1700                 g_signal_connect (dialog, "response",
1701                                   G_CALLBACK (gtk_widget_destroy),
1702                                   NULL);
1703                 gtk_window_present (GTK_WINDOW (dialog));
1704
1705                 g_clear_error (&error);
1706         }
1707
1708         g_free (real_url);
1709 }
1710
1711 void
1712 empathy_send_file (EmpathyContact *contact, GFile *file)
1713 {
1714         EmpathyFTFactory *factory;
1715         GtkRecentManager *manager;
1716         gchar *uri;
1717
1718         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1719         g_return_if_fail (G_IS_FILE (file));
1720
1721         factory = empathy_ft_factory_dup_singleton ();
1722
1723         empathy_ft_factory_new_transfer_outgoing (factory, contact, file);
1724
1725         uri = g_file_get_uri (file);
1726         manager = gtk_recent_manager_get_default ();
1727         gtk_recent_manager_add_item (manager, uri);
1728         g_free (uri);
1729
1730         g_object_unref (factory);
1731 }
1732
1733 void
1734 empathy_send_file_from_uri_list (EmpathyContact *contact, const gchar *uri_list)
1735 {
1736         const gchar *nl;
1737         GFile *file;
1738
1739         /* Only handle a single file for now.  It would be wicked cool to be
1740            able to do multiple files, offering to zip them or whatever like
1741            nautilus-sendto does.  Note that text/uri-list is defined to have
1742            each line terminated by \r\n, but we can be tolerant of applications
1743            that only use \n or don't terminate single-line entries.
1744         */
1745         nl = strstr (uri_list, "\r\n");
1746         if (!nl) {
1747                 nl = strchr (uri_list, '\n');
1748         }
1749         if (nl) {
1750                 gchar *uri = g_strndup (uri_list, nl - uri_list);
1751                 file = g_file_new_for_uri (uri);
1752                 g_free (uri);
1753         }
1754         else {
1755                 file = g_file_new_for_uri (uri_list);
1756         }
1757
1758         empathy_send_file (contact, file);
1759
1760         g_object_unref (file);
1761 }
1762
1763 static void
1764 file_manager_send_file_response_cb (GtkDialog      *widget,
1765                                     gint            response_id,
1766                                     EmpathyContact *contact)
1767 {
1768         GFile *file;
1769
1770         if (response_id == GTK_RESPONSE_OK) {
1771                 file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (widget));
1772
1773                 empathy_send_file (contact, file);
1774
1775                 g_object_unref (file);
1776         }
1777
1778         gtk_widget_destroy (GTK_WIDGET (widget));
1779 }
1780
1781 void
1782 empathy_send_file_with_file_chooser (EmpathyContact *contact)
1783 {
1784         GtkWidget               *widget;
1785         GtkWidget               *button;
1786
1787         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1788
1789         DEBUG ("Creating selection file chooser");
1790
1791         widget = gtk_file_chooser_dialog_new (_("Select a file"),
1792                                               NULL,
1793                                               GTK_FILE_CHOOSER_ACTION_OPEN,
1794                                               GTK_STOCK_CANCEL,
1795                                               GTK_RESPONSE_CANCEL,
1796                                               NULL);
1797
1798         /* send button */
1799         button = gtk_button_new_with_mnemonic (_("_Send"));
1800         gtk_button_set_image (GTK_BUTTON (button),
1801                 gtk_image_new_from_icon_name (EMPATHY_IMAGE_DOCUMENT_SEND,
1802                                               GTK_ICON_SIZE_BUTTON));
1803         gtk_widget_show (button);
1804         gtk_dialog_add_action_widget (GTK_DIALOG (widget), button,
1805                                       GTK_RESPONSE_OK);
1806         gtk_widget_set_can_default (button, TRUE);
1807         gtk_dialog_set_default_response (GTK_DIALOG (widget),
1808                                          GTK_RESPONSE_OK);
1809
1810         gtk_file_chooser_set_local_only (GTK_FILE_CHOOSER (widget), FALSE);
1811
1812         gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (widget),
1813                 g_get_home_dir ());
1814
1815         g_signal_connect (widget, "response",
1816                           G_CALLBACK (file_manager_send_file_response_cb),
1817                           contact);
1818
1819         gtk_widget_show (widget);
1820 }
1821
1822 static void
1823 file_manager_receive_file_response_cb (GtkDialog *dialog,
1824                                        GtkResponseType response,
1825                                        EmpathyFTHandler *handler)
1826 {
1827         EmpathyFTFactory *factory;
1828         GFile *file;
1829
1830         if (response == GTK_RESPONSE_OK) {
1831                 factory = empathy_ft_factory_dup_singleton ();
1832                 file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (dialog));
1833
1834                 empathy_ft_factory_set_destination_for_incoming_handler
1835                         (factory, handler, file);
1836
1837                 g_object_unref (factory);
1838                 g_object_unref (file);
1839         } else {
1840                 /* unref the handler, as we dismissed the file chooser,
1841                  * and refused the transfer.
1842                  */
1843                 g_object_unref (handler);
1844         }
1845
1846         gtk_widget_destroy (GTK_WIDGET (dialog));
1847 }
1848
1849 void
1850 empathy_receive_file_with_file_chooser (EmpathyFTHandler *handler)
1851 {
1852         GtkWidget *widget;
1853         const gchar *dir;
1854         EmpathyContact *contact;
1855         gchar *title;
1856
1857         contact = empathy_ft_handler_get_contact (handler);
1858         g_assert (contact != NULL);
1859
1860         title = g_strdup_printf (_("Incoming file from %s"),
1861                 empathy_contact_get_name (contact));
1862
1863         widget = gtk_file_chooser_dialog_new (title,
1864                                               NULL,
1865                                               GTK_FILE_CHOOSER_ACTION_SAVE,
1866                                               GTK_STOCK_CANCEL,
1867                                               GTK_RESPONSE_CANCEL,
1868                                               GTK_STOCK_SAVE,
1869                                               GTK_RESPONSE_OK,
1870                                               NULL);
1871         gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (widget),
1872                 empathy_ft_handler_get_filename (handler));
1873         gtk_file_chooser_set_do_overwrite_confirmation
1874                 (GTK_FILE_CHOOSER (widget), TRUE);
1875
1876         dir = g_get_user_special_dir (G_USER_DIRECTORY_DOWNLOAD);
1877         if (dir == NULL)
1878                 /* Fallback to $HOME if $XDG_DOWNLOAD_DIR is not set */
1879                 dir = g_get_home_dir ();
1880
1881         gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (widget), dir);
1882
1883         g_signal_connect (widget, "response",
1884                 G_CALLBACK (file_manager_receive_file_response_cb), handler);
1885
1886         gtk_widget_show (widget);
1887         g_free (title);
1888 }