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