]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-ui-utils.c
Fix warnings from GCC 4.6 about variables that are set but not used.
[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-ft-factory.h>
53
54 void
55 empathy_gtk_init (void)
56 {
57         static gboolean initialized = FALSE;
58
59         if (initialized)
60                 return;
61
62         empathy_init ();
63         gtk_icon_theme_append_search_path (gtk_icon_theme_get_default (),
64                                            PKGDATADIR G_DIR_SEPARATOR_S "icons");
65
66         initialized = TRUE;
67 }
68
69 static GtkBuilder *
70 builder_get_file_valist (const gchar *filename,
71                          const gchar *first_object,
72                          va_list      args)
73 {
74         GtkBuilder  *gui;
75         const gchar *name;
76         GObject    **object_ptr;
77         GError      *error = NULL;
78
79         DEBUG ("Loading file %s", filename);
80
81         gui = gtk_builder_new ();
82         gtk_builder_set_translation_domain (gui, GETTEXT_PACKAGE);
83         if (!gtk_builder_add_from_file (gui, filename, &error)) {
84                 g_critical ("GtkBuilder Error (%s): %s",
85                                 filename, error->message);
86                 g_clear_error (&error);
87                 g_object_unref (gui);
88
89                 /* we need to iterate and set all of the pointers to NULL */
90                 for (name = first_object; name;
91                      name = va_arg (args, const gchar *)) {
92                         object_ptr = va_arg (args, GObject**);
93
94                         *object_ptr = NULL;
95                 }
96
97                 return NULL;
98         }
99
100         for (name = first_object; name; name = va_arg (args, const gchar *)) {
101                 object_ptr = va_arg (args, GObject**);
102
103                 *object_ptr = gtk_builder_get_object (gui, name);
104
105                 if (!*object_ptr) {
106                         g_warning ("File is missing object '%s'.", name);
107                         continue;
108                 }
109         }
110
111         return gui;
112 }
113
114 GtkBuilder *
115 empathy_builder_get_file (const gchar *filename,
116                           const gchar *first_object,
117                           ...)
118 {
119         GtkBuilder *gui;
120         va_list     args;
121
122         va_start (args, first_object);
123         gui = builder_get_file_valist (filename, first_object, args);
124         va_end (args);
125
126         return gui;
127 }
128
129 void
130 empathy_builder_connect (GtkBuilder  *gui,
131                          gpointer     user_data,
132                          const gchar *first_object,
133                          ...)
134 {
135         va_list      args;
136         const gchar *name;
137         const gchar *sig;
138         GObject     *object;
139         GCallback    callback;
140
141         va_start (args, first_object);
142         for (name = first_object; name; name = va_arg (args, const gchar *)) {
143                 sig = va_arg (args, const gchar *);
144                 callback = va_arg (args, GCallback);
145
146                 object = gtk_builder_get_object (gui, name);
147                 if (!object) {
148                         g_warning ("File is missing object '%s'.", name);
149                         continue;
150                 }
151
152                 g_signal_connect (object, sig, callback, user_data);
153         }
154
155         va_end (args);
156 }
157
158 GtkWidget *
159 empathy_builder_unref_and_keep_widget (GtkBuilder *gui,
160                                        GtkWidget  *widget)
161 {
162         /* On construction gui sinks the initial reference to widget. When gui
163          * is finalized it will drop its ref to widget. We take our own ref to
164          * prevent widget being finalised. The widget is forced to have a
165          * floating reference, like when it was initially unowned so that it can
166          * be used like any other GtkWidget. */
167
168         g_object_ref (widget);
169         g_object_force_floating (G_OBJECT (widget));
170         g_object_unref (gui);
171
172         return widget;
173 }
174
175 const gchar *
176 empathy_icon_name_for_presence (TpConnectionPresenceType presence)
177 {
178         switch (presence) {
179         case TP_CONNECTION_PRESENCE_TYPE_AVAILABLE:
180                 return EMPATHY_IMAGE_AVAILABLE;
181         case TP_CONNECTION_PRESENCE_TYPE_BUSY:
182                 return EMPATHY_IMAGE_BUSY;
183         case TP_CONNECTION_PRESENCE_TYPE_AWAY:
184                 return EMPATHY_IMAGE_AWAY;
185         case TP_CONNECTION_PRESENCE_TYPE_EXTENDED_AWAY:
186                 if (gtk_icon_theme_has_icon (gtk_icon_theme_get_default (),
187                                              EMPATHY_IMAGE_EXT_AWAY))
188                         return EMPATHY_IMAGE_EXT_AWAY;
189
190                 /* The 'extended-away' icon is not an official one so we fallback to idle if
191                  * it's not implemented */
192                 return EMPATHY_IMAGE_IDLE;
193         case TP_CONNECTION_PRESENCE_TYPE_HIDDEN:
194                 if (gtk_icon_theme_has_icon (gtk_icon_theme_get_default (),
195                                              EMPATHY_IMAGE_HIDDEN))
196                         return EMPATHY_IMAGE_HIDDEN;
197
198                 /* The 'hidden' icon is not an official one so we fallback to offline if
199                  * it's not implemented */
200                 return EMPATHY_IMAGE_OFFLINE;
201         case TP_CONNECTION_PRESENCE_TYPE_OFFLINE:
202         case TP_CONNECTION_PRESENCE_TYPE_ERROR:
203                 return EMPATHY_IMAGE_OFFLINE;
204         case TP_CONNECTION_PRESENCE_TYPE_UNKNOWN:
205                 return EMPATHY_IMAGE_PENDING;
206         case TP_CONNECTION_PRESENCE_TYPE_UNSET:
207         default:
208                 return NULL;
209         }
210
211         return NULL;
212 }
213
214 const gchar *
215 empathy_icon_name_for_contact (EmpathyContact *contact)
216 {
217         TpConnectionPresenceType presence;
218
219         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact),
220                               EMPATHY_IMAGE_OFFLINE);
221
222         presence = empathy_contact_get_presence (contact);
223         return empathy_icon_name_for_presence (presence);
224 }
225
226 const gchar *
227 empathy_icon_name_for_individual (FolksIndividual *individual)
228 {
229         FolksPresenceType folks_presence;
230         TpConnectionPresenceType presence;
231
232         folks_presence =
233             folks_presence_details_get_presence_type (
234                 FOLKS_PRESENCE_DETAILS (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 height, rowstride, i;
409         guchar *pixels;
410         guchar *row;
411
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 = NULL;
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), g_object_unref);
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                 gint                 width,
620                 gint                 height,
621                 GCancellable        *cancellable,
622                 GAsyncReadyCallback  callback,
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 =
634                 folks_avatar_details_get_avatar (FOLKS_AVATAR_DETAILS (individual));
635         if (avatar_file == NULL)
636                 goto out;
637
638         closure = pixbuf_avatar_from_individual_closure_new (individual, result,
639                                                              width, height);
640         if (closure == NULL)
641                 goto out;
642
643         g_file_load_contents_async (avatar_file, cancellable,
644                         avatar_file_load_contents_cb, closure);
645
646         g_object_unref (result);
647
648         return;
649
650 out:
651         g_simple_async_result_set_op_res_gpointer (result, NULL, NULL);
652         g_simple_async_result_complete (result);
653         g_object_unref (result);
654 }
655
656 /* Return a ref on the GdkPixbuf */
657 GdkPixbuf *
658 empathy_pixbuf_avatar_from_individual_scaled_finish (
659                 FolksIndividual *individual,
660                 GAsyncResult *result,
661                 GError **error)
662 {
663         GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
664         gboolean result_valid;
665         GdkPixbuf *pixbuf;
666
667         g_return_val_if_fail (FOLKS_IS_INDIVIDUAL (individual), NULL);
668         g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (simple), NULL);
669
670         if (g_simple_async_result_propagate_error (simple, error))
671                 return NULL;
672
673         result_valid = g_simple_async_result_is_valid (result,
674                         G_OBJECT (individual),
675                         empathy_pixbuf_avatar_from_individual_scaled_async);
676         g_return_val_if_fail (result_valid, NULL);
677
678         pixbuf = g_simple_async_result_get_op_res_gpointer (simple);
679         return pixbuf != NULL ? g_object_ref (pixbuf) : NULL;
680 }
681
682 GdkPixbuf *
683 empathy_pixbuf_contact_status_icon (EmpathyContact *contact,
684                                    gboolean       show_protocol)
685 {
686         const gchar *icon_name;
687
688         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
689
690         icon_name = empathy_icon_name_for_contact (contact);
691
692         if (icon_name == NULL) {
693                 return NULL;
694         }
695         return empathy_pixbuf_contact_status_icon_with_icon_name (contact,
696             icon_name,
697             show_protocol);
698 }
699
700 GdkPixbuf *
701 empathy_pixbuf_contact_status_icon_with_icon_name (EmpathyContact *contact,
702                                           const gchar    *icon_name,
703                                           gboolean       show_protocol)
704 {
705         GdkPixbuf *pix_status;
706         GdkPixbuf *pix_protocol;
707         gchar     *icon_filename;
708         gint       height, width;
709         gint       numerator, denominator;
710
711         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact) ||
712                         (show_protocol == FALSE), NULL);
713         g_return_val_if_fail (icon_name != NULL, NULL);
714
715         numerator = 3;
716         denominator = 4;
717
718         icon_filename = empathy_filename_from_icon_name (icon_name,
719                                                          GTK_ICON_SIZE_MENU);
720         if (icon_filename == NULL) {
721                 DEBUG ("icon name: %s could not be found\n", icon_name);
722                 return NULL;
723         }
724
725         pix_status = gdk_pixbuf_new_from_file (icon_filename, NULL);
726
727         if (pix_status == NULL) {
728                 DEBUG ("Could not open icon %s\n", icon_filename);
729                 g_free (icon_filename);
730                 return NULL;
731         }
732
733         g_free (icon_filename);
734
735         if (!show_protocol)
736                 return pix_status;
737
738         height = gdk_pixbuf_get_height (pix_status);
739         width = gdk_pixbuf_get_width (pix_status);
740
741         pix_protocol = empathy_pixbuf_protocol_from_contact_scaled (contact,
742                                                                     width * numerator / denominator,
743                                                                     height * numerator / denominator);
744
745         if (pix_protocol == NULL) {
746                 return pix_status;
747         }
748         gdk_pixbuf_composite (pix_protocol, pix_status,
749             0, height - height * numerator / denominator,
750             width * numerator / denominator, height * numerator / denominator,
751             0, height - height * numerator / denominator,
752             1, 1,
753             GDK_INTERP_BILINEAR, 255);
754
755         g_object_unref (pix_protocol);
756
757         return pix_status;
758 }
759
760 GdkPixbuf *
761 empathy_pixbuf_protocol_from_contact_scaled (EmpathyContact *contact,
762                                           gint           width,
763                                           gint           height)
764 {
765         TpAccount *account;
766         gchar     *filename;
767         GdkPixbuf *pixbuf = NULL;
768
769         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
770
771         account = empathy_contact_get_account (contact);
772         filename = empathy_filename_from_icon_name (tp_account_get_icon_name (account),
773                                                     GTK_ICON_SIZE_MENU);
774         if (filename != NULL) {
775                 pixbuf = gdk_pixbuf_new_from_file_at_size (filename, width, height, NULL);
776                 g_free (filename);
777         }
778
779         return pixbuf;
780 }
781
782 GdkPixbuf *
783 empathy_pixbuf_scale_down_if_necessary (GdkPixbuf *pixbuf, gint max_size)
784 {
785         gint      width, height;
786         gdouble   factor;
787
788         width = gdk_pixbuf_get_width (pixbuf);
789         height = gdk_pixbuf_get_height (pixbuf);
790
791         if (width > 0 && (width > max_size || height > max_size)) {
792                 factor = (gdouble) max_size / MAX (width, height);
793
794                 width = width * factor;
795                 height = height * factor;
796
797                 return gdk_pixbuf_scale_simple (pixbuf,
798                                                 width, height,
799                                                 GDK_INTERP_HYPER);
800         }
801
802         return g_object_ref (pixbuf);
803 }
804
805 GdkPixbuf *
806 empathy_pixbuf_from_icon_name_sized (const gchar *icon_name,
807                                      gint size)
808 {
809         GtkIconTheme *theme;
810         GdkPixbuf *pixbuf;
811         GError *error = NULL;
812
813         if (!icon_name) {
814                 return NULL;
815         }
816
817         theme = gtk_icon_theme_get_default ();
818
819         pixbuf = gtk_icon_theme_load_icon (theme,
820                                            icon_name,
821                                            size,
822                                            0,
823                                            &error);
824         if (error) {
825                 DEBUG ("Error loading icon: %s", error->message);
826                 g_clear_error (&error);
827         }
828
829         return pixbuf;
830 }
831
832 GdkPixbuf *
833 empathy_pixbuf_from_icon_name (const gchar *icon_name,
834                                GtkIconSize  icon_size)
835 {
836         gint  w, h;
837         gint  size = 48;
838
839         if (!icon_name) {
840                 return NULL;
841         }
842
843         if (gtk_icon_size_lookup (icon_size, &w, &h)) {
844                 size = (w + h) / 2;
845         }
846
847         return empathy_pixbuf_from_icon_name_sized (icon_name, size);
848 }
849
850 gchar *
851 empathy_filename_from_icon_name (const gchar *icon_name,
852                                  GtkIconSize  icon_size)
853 {
854         GtkIconTheme *icon_theme;
855         GtkIconInfo  *icon_info;
856         gint          w, h;
857         gint          size = 48;
858         gchar        *ret;
859
860         icon_theme = gtk_icon_theme_get_default ();
861
862         if (gtk_icon_size_lookup (icon_size, &w, &h)) {
863                 size = (w + h) / 2;
864         }
865
866         icon_info = gtk_icon_theme_lookup_icon (icon_theme, icon_name, size, 0);
867         ret = g_strdup (gtk_icon_info_get_filename (icon_info));
868         gtk_icon_info_free (icon_info);
869
870         return ret;
871 }
872
873 /* Stolen from GtkSourceView, hence the weird intendation. Please keep it like
874  * that to make it easier to apply changes from the original code.
875  */
876 #define GTK_TEXT_UNKNOWN_CHAR 0xFFFC
877
878 /* this function acts like g_utf8_offset_to_pointer() except that if it finds a
879  * decomposable character it consumes the decomposition length from the given
880  * offset.  So it's useful when the offset was calculated for the normalized
881  * version of str, but we need a pointer to str itself. */
882 static const gchar *
883 pointer_from_offset_skipping_decomp (const gchar *str, gint offset)
884 {
885         gchar *casefold, *normal;
886         const gchar *p, *q;
887
888         p = str;
889         while (offset > 0)
890         {
891                 q = g_utf8_next_char (p);
892                 casefold = g_utf8_casefold (p, q - p);
893                 normal = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
894                 offset -= g_utf8_strlen (normal, -1);
895                 g_free (casefold);
896                 g_free (normal);
897                 p = q;
898         }
899         return p;
900 }
901
902 static const gchar *
903 g_utf8_strcasestr (const gchar *haystack, const gchar *needle)
904 {
905         gsize needle_len;
906         gsize haystack_len;
907         const gchar *ret = NULL;
908         gchar *p;
909         gchar *casefold;
910         gchar *caseless_haystack;
911         gint i;
912
913         g_return_val_if_fail (haystack != NULL, NULL);
914         g_return_val_if_fail (needle != NULL, NULL);
915
916         casefold = g_utf8_casefold (haystack, -1);
917         caseless_haystack = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
918         g_free (casefold);
919
920         needle_len = g_utf8_strlen (needle, -1);
921         haystack_len = g_utf8_strlen (caseless_haystack, -1);
922
923         if (needle_len == 0)
924         {
925                 ret = (gchar *) haystack;
926                 goto finally_1;
927         }
928
929         if (haystack_len < needle_len)
930         {
931                 ret = NULL;
932                 goto finally_1;
933         }
934
935         p = (gchar *) caseless_haystack;
936         needle_len = strlen (needle);
937         i = 0;
938
939         while (*p)
940         {
941                 if ((strncmp (p, needle, needle_len) == 0))
942                 {
943                         ret = pointer_from_offset_skipping_decomp (haystack, i);
944                         goto finally_1;
945                 }
946
947                 p = g_utf8_next_char (p);
948                 i++;
949         }
950
951 finally_1:
952         g_free (caseless_haystack);
953
954         return ret;
955 }
956
957 static gboolean
958 g_utf8_caselessnmatch (const char *s1, const char *s2,
959                        gssize n1, gssize n2)
960 {
961         gchar *casefold;
962         gchar *normalized_s1;
963         gchar *normalized_s2;
964         gint len_s1;
965         gint len_s2;
966         gboolean ret = FALSE;
967
968         g_return_val_if_fail (s1 != NULL, FALSE);
969         g_return_val_if_fail (s2 != NULL, FALSE);
970         g_return_val_if_fail (n1 > 0, FALSE);
971         g_return_val_if_fail (n2 > 0, FALSE);
972
973         casefold = g_utf8_casefold (s1, n1);
974         normalized_s1 = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
975         g_free (casefold);
976
977         casefold = g_utf8_casefold (s2, n2);
978         normalized_s2 = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
979         g_free (casefold);
980
981         len_s1 = strlen (normalized_s1);
982         len_s2 = strlen (normalized_s2);
983
984         if (len_s1 < len_s2)
985                 goto finally_2;
986
987         ret = (strncmp (normalized_s1, normalized_s2, len_s2) == 0);
988
989 finally_2:
990         g_free (normalized_s1);
991         g_free (normalized_s2);
992
993         return ret;
994 }
995
996 static void
997 forward_chars_with_skipping (GtkTextIter *iter,
998                              gint         count,
999                              gboolean     skip_invisible,
1000                              gboolean     skip_nontext,
1001                              gboolean     skip_decomp)
1002 {
1003         gint i;
1004
1005         g_return_if_fail (count >= 0);
1006
1007         i = count;
1008
1009         while (i > 0)
1010         {
1011                 gboolean ignored = FALSE;
1012
1013                 /* minimal workaround to avoid the infinite loop of bug #168247.
1014                  * It doesn't fix the problemjust the symptom...
1015                  */
1016                 if (gtk_text_iter_is_end (iter))
1017                         return;
1018
1019                 if (skip_nontext && gtk_text_iter_get_char (iter) == GTK_TEXT_UNKNOWN_CHAR)
1020                         ignored = TRUE;
1021
1022                 if (!ignored && skip_invisible &&
1023                     /* _gtk_text_btree_char_is_invisible (iter)*/ FALSE)
1024                         ignored = TRUE;
1025
1026                 if (!ignored && skip_decomp)
1027                 {
1028                         /* being UTF8 correct sucks; this accounts for extra
1029                            offsets coming from canonical decompositions of
1030                            UTF8 characters (e.g. accented characters) which
1031                            g_utf8_normalize () performs */
1032                         gchar *normal;
1033                         gchar buffer[6];
1034                         gint buffer_len;
1035
1036                         buffer_len = g_unichar_to_utf8 (gtk_text_iter_get_char (iter), buffer);
1037                         normal = g_utf8_normalize (buffer, buffer_len, G_NORMALIZE_NFD);
1038                         i -= (g_utf8_strlen (normal, -1) - 1);
1039                         g_free (normal);
1040                 }
1041
1042                 gtk_text_iter_forward_char (iter);
1043
1044                 if (!ignored)
1045                         --i;
1046         }
1047 }
1048
1049 static gboolean
1050 lines_match (const GtkTextIter *start,
1051              const gchar      **lines,
1052              gboolean           visible_only,
1053              gboolean           slice,
1054              GtkTextIter       *match_start,
1055              GtkTextIter       *match_end)
1056 {
1057         GtkTextIter next;
1058         gchar *line_text;
1059         const gchar *found;
1060         gint offset;
1061
1062         if (*lines == NULL || **lines == '\0')
1063         {
1064                 if (match_start)
1065                         *match_start = *start;
1066                 if (match_end)
1067                         *match_end = *start;
1068                 return TRUE;
1069         }
1070
1071         next = *start;
1072         gtk_text_iter_forward_line (&next);
1073
1074         /* No more text in buffer, but *lines is nonempty */
1075         if (gtk_text_iter_equal (start, &next))
1076                 return FALSE;
1077
1078         if (slice)
1079         {
1080                 if (visible_only)
1081                         line_text = gtk_text_iter_get_visible_slice (start, &next);
1082                 else
1083                         line_text = gtk_text_iter_get_slice (start, &next);
1084         }
1085         else
1086         {
1087                 if (visible_only)
1088                         line_text = gtk_text_iter_get_visible_text (start, &next);
1089                 else
1090                         line_text = gtk_text_iter_get_text (start, &next);
1091         }
1092
1093         if (match_start) /* if this is the first line we're matching */
1094         {
1095                 found = g_utf8_strcasestr (line_text, *lines);
1096         }
1097         else
1098         {
1099                 /* If it's not the first line, we have to match from the
1100                  * start of the line.
1101                  */
1102                 if (g_utf8_caselessnmatch (line_text, *lines, strlen (line_text),
1103                                            strlen (*lines)))
1104                         found = line_text;
1105                 else
1106                         found = NULL;
1107         }
1108
1109         if (found == NULL)
1110         {
1111                 g_free (line_text);
1112                 return FALSE;
1113         }
1114
1115         /* Get offset to start of search string */
1116         offset = g_utf8_strlen (line_text, found - line_text);
1117
1118         next = *start;
1119
1120         /* If match start needs to be returned, set it to the
1121          * start of the search string.
1122          */
1123         forward_chars_with_skipping (&next, offset, visible_only, !slice, FALSE);
1124         if (match_start)
1125         {
1126                 *match_start = next;
1127         }
1128
1129         /* Go to end of search string */
1130         forward_chars_with_skipping (&next, g_utf8_strlen (*lines, -1), visible_only, !slice, TRUE);
1131
1132         g_free (line_text);
1133
1134         ++lines;
1135
1136         if (match_end)
1137                 *match_end = next;
1138
1139         /* pass NULL for match_start, since we don't need to find the
1140          * start again.
1141          */
1142         return lines_match (&next, lines, visible_only, slice, NULL, match_end);
1143 }
1144
1145 /* strsplit () that retains the delimiter as part of the string. */
1146 static gchar **
1147 strbreakup (const char *string,
1148             const char *delimiter,
1149             gint        max_tokens)
1150 {
1151         GSList *string_list = NULL, *slist;
1152         gchar **str_array, *s, *casefold, *new_string;
1153         guint i, n = 1;
1154
1155         g_return_val_if_fail (string != NULL, NULL);
1156         g_return_val_if_fail (delimiter != NULL, NULL);
1157
1158         if (max_tokens < 1)
1159                 max_tokens = G_MAXINT;
1160
1161         s = strstr (string, delimiter);
1162         if (s)
1163         {
1164                 guint delimiter_len = strlen (delimiter);
1165
1166                 do
1167                 {
1168                         guint len;
1169
1170                         len = s - string + delimiter_len;
1171                         new_string = g_new (gchar, len + 1);
1172                         strncpy (new_string, string, len);
1173                         new_string[len] = 0;
1174                         casefold = g_utf8_casefold (new_string, -1);
1175                         g_free (new_string);
1176                         new_string = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1177                         g_free (casefold);
1178                         string_list = g_slist_prepend (string_list, new_string);
1179                         n++;
1180                         string = s + delimiter_len;
1181                         s = strstr (string, delimiter);
1182                 } while (--max_tokens && s);
1183         }
1184
1185         if (*string)
1186         {
1187                 n++;
1188                 casefold = g_utf8_casefold (string, -1);
1189                 new_string = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1190                 g_free (casefold);
1191                 string_list = g_slist_prepend (string_list, new_string);
1192         }
1193
1194         str_array = g_new (gchar*, n);
1195
1196         i = n - 1;
1197
1198         str_array[i--] = NULL;
1199         for (slist = string_list; slist; slist = slist->next)
1200                 str_array[i--] = slist->data;
1201
1202         g_slist_free (string_list);
1203
1204         return str_array;
1205 }
1206
1207 gboolean
1208 empathy_text_iter_forward_search (const GtkTextIter   *iter,
1209                                  const gchar         *str,
1210                                  GtkTextIter         *match_start,
1211                                  GtkTextIter         *match_end,
1212                                  const GtkTextIter   *limit)
1213 {
1214         gchar **lines = NULL;
1215         GtkTextIter match;
1216         gboolean retval = FALSE;
1217         GtkTextIter search;
1218         gboolean visible_only;
1219         gboolean slice;
1220
1221         g_return_val_if_fail (iter != NULL, FALSE);
1222         g_return_val_if_fail (str != NULL, FALSE);
1223
1224         if (limit && gtk_text_iter_compare (iter, limit) >= 0)
1225                 return FALSE;
1226
1227         if (*str == '\0') {
1228                 /* If we can move one char, return the empty string there */
1229                 match = *iter;
1230
1231                 if (gtk_text_iter_forward_char (&match)) {
1232                         if (limit && gtk_text_iter_equal (&match, limit)) {
1233                                 return FALSE;
1234                         }
1235
1236                         if (match_start) {
1237                                 *match_start = match;
1238                         }
1239                         if (match_end) {
1240                                 *match_end = match;
1241                         }
1242                         return TRUE;
1243                 } else {
1244                         return FALSE;
1245                 }
1246         }
1247
1248         visible_only = TRUE;
1249         slice = FALSE;
1250
1251         /* locate all lines */
1252         lines = strbreakup (str, "\n", -1);
1253
1254         search = *iter;
1255
1256         do {
1257                 /* This loop has an inefficient worst-case, where
1258                  * gtk_text_iter_get_text () is called repeatedly on
1259                  * a single line.
1260                  */
1261                 GtkTextIter end;
1262
1263                 if (limit && gtk_text_iter_compare (&search, limit) >= 0) {
1264                         break;
1265                 }
1266
1267                 if (lines_match (&search, (const gchar**)lines,
1268                                  visible_only, slice, &match, &end)) {
1269                         if (limit == NULL ||
1270                             (limit && gtk_text_iter_compare (&end, limit) <= 0)) {
1271                                 retval = TRUE;
1272
1273                                 if (match_start) {
1274                                         *match_start = match;
1275                                 }
1276                                 if (match_end) {
1277                                         *match_end = end;
1278                                 }
1279                         }
1280                         break;
1281                 }
1282         } while (gtk_text_iter_forward_line (&search));
1283
1284         g_strfreev ((gchar **) lines);
1285
1286         return retval;
1287 }
1288
1289 static const gchar *
1290 g_utf8_strrcasestr (const gchar *haystack, const gchar *needle)
1291 {
1292         gsize needle_len;
1293         gsize haystack_len;
1294         const gchar *ret = NULL;
1295         gchar *p;
1296         gchar *casefold;
1297         gchar *caseless_haystack;
1298         gint i;
1299
1300         g_return_val_if_fail (haystack != NULL, NULL);
1301         g_return_val_if_fail (needle != NULL, NULL);
1302
1303         casefold = g_utf8_casefold (haystack, -1);
1304         caseless_haystack = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1305         g_free (casefold);
1306
1307         needle_len = g_utf8_strlen (needle, -1);
1308         haystack_len = g_utf8_strlen (caseless_haystack, -1);
1309
1310         if (needle_len == 0)
1311         {
1312                 ret = (gchar *) haystack;
1313                 goto finally_1;
1314         }
1315
1316         if (haystack_len < needle_len)
1317         {
1318                 ret = NULL;
1319                 goto finally_1;
1320         }
1321
1322         i = haystack_len - needle_len;
1323         p = g_utf8_offset_to_pointer (caseless_haystack, i);
1324         needle_len = strlen (needle);
1325
1326         while (p >= caseless_haystack)
1327         {
1328                 if (strncmp (p, needle, needle_len) == 0)
1329                 {
1330                         ret = pointer_from_offset_skipping_decomp (haystack, i);
1331                         goto finally_1;
1332                 }
1333
1334                 p = g_utf8_prev_char (p);
1335                 i--;
1336         }
1337
1338 finally_1:
1339         g_free (caseless_haystack);
1340
1341         return ret;
1342 }
1343
1344 static gboolean
1345 backward_lines_match (const GtkTextIter *start,
1346                       const gchar      **lines,
1347                       gboolean           visible_only,
1348                       gboolean           slice,
1349                       GtkTextIter       *match_start,
1350                       GtkTextIter       *match_end)
1351 {
1352         GtkTextIter line, next;
1353         gchar *line_text;
1354         const gchar *found;
1355         gint offset;
1356
1357         if (*lines == NULL || **lines == '\0')
1358         {
1359                 if (match_start)
1360                         *match_start = *start;
1361                 if (match_end)
1362                         *match_end = *start;
1363                 return TRUE;
1364         }
1365
1366         line = next = *start;
1367         if (gtk_text_iter_get_line_offset (&next) == 0)
1368         {
1369                 if (!gtk_text_iter_backward_line (&next))
1370                         return FALSE;
1371         }
1372         else
1373                 gtk_text_iter_set_line_offset (&next, 0);
1374
1375         if (slice)
1376         {
1377                 if (visible_only)
1378                         line_text = gtk_text_iter_get_visible_slice (&next, &line);
1379                 else
1380                         line_text = gtk_text_iter_get_slice (&next, &line);
1381         }
1382         else
1383         {
1384                 if (visible_only)
1385                         line_text = gtk_text_iter_get_visible_text (&next, &line);
1386                 else
1387                         line_text = gtk_text_iter_get_text (&next, &line);
1388         }
1389
1390         if (match_start) /* if this is the first line we're matching */
1391         {
1392                 found = g_utf8_strrcasestr (line_text, *lines);
1393         }
1394         else
1395         {
1396                 /* If it's not the first line, we have to match from the
1397                  * start of the line.
1398                  */
1399                 if (g_utf8_caselessnmatch (line_text, *lines, strlen (line_text),
1400                                            strlen (*lines)))
1401                         found = line_text;
1402                 else
1403                         found = NULL;
1404         }
1405
1406         if (found == NULL)
1407         {
1408                 g_free (line_text);
1409                 return FALSE;
1410         }
1411
1412         /* Get offset to start of search string */
1413         offset = g_utf8_strlen (line_text, found - line_text);
1414
1415         forward_chars_with_skipping (&next, offset, visible_only, !slice, FALSE);
1416
1417         /* If match start needs to be returned, set it to the
1418          * start of the search string.
1419          */
1420         if (match_start)
1421         {
1422                 *match_start = next;
1423         }
1424
1425         /* Go to end of search string */
1426         forward_chars_with_skipping (&next, g_utf8_strlen (*lines, -1), visible_only, !slice, TRUE);
1427
1428         g_free (line_text);
1429
1430         ++lines;
1431
1432         if (match_end)
1433                 *match_end = next;
1434
1435         /* try to match the rest of the lines forward, passing NULL
1436          * for match_start so lines_match will try to match the entire
1437          * line */
1438         return lines_match (&next, lines, visible_only,
1439                             slice, NULL, match_end);
1440 }
1441
1442 gboolean
1443 empathy_text_iter_backward_search (const GtkTextIter   *iter,
1444                                   const gchar         *str,
1445                                   GtkTextIter         *match_start,
1446                                   GtkTextIter         *match_end,
1447                                   const GtkTextIter   *limit)
1448 {
1449         gchar **lines = NULL;
1450         GtkTextIter match;
1451         gboolean retval = FALSE;
1452         GtkTextIter search;
1453         gboolean visible_only;
1454         gboolean slice;
1455
1456         g_return_val_if_fail (iter != NULL, FALSE);
1457         g_return_val_if_fail (str != NULL, FALSE);
1458
1459         if (limit && gtk_text_iter_compare (iter, limit) <= 0)
1460                 return FALSE;
1461
1462         if (*str == '\0')
1463         {
1464                 /* If we can move one char, return the empty string there */
1465                 match = *iter;
1466
1467                 if (gtk_text_iter_backward_char (&match))
1468                 {
1469                         if (limit && gtk_text_iter_equal (&match, limit))
1470                                 return FALSE;
1471
1472                         if (match_start)
1473                                 *match_start = match;
1474                         if (match_end)
1475                                 *match_end = match;
1476                         return TRUE;
1477                 }
1478                 else
1479                 {
1480                         return FALSE;
1481                 }
1482         }
1483
1484         visible_only = TRUE;
1485         slice = TRUE;
1486
1487         /* locate all lines */
1488         lines = strbreakup (str, "\n", -1);
1489
1490         search = *iter;
1491
1492         while (TRUE)
1493         {
1494                 /* This loop has an inefficient worst-case, where
1495                  * gtk_text_iter_get_text () is called repeatedly on
1496                  * a single line.
1497                  */
1498                 GtkTextIter end;
1499
1500                 if (limit && gtk_text_iter_compare (&search, limit) <= 0)
1501                         break;
1502
1503                 if (backward_lines_match (&search, (const gchar**)lines,
1504                                           visible_only, slice, &match, &end))
1505                 {
1506                         if (limit == NULL || (limit &&
1507                                               gtk_text_iter_compare (&end, limit) > 0))
1508                         {
1509                                 retval = TRUE;
1510
1511                                 if (match_start)
1512                                         *match_start = match;
1513                                 if (match_end)
1514                                         *match_end = end;
1515                         }
1516                         break;
1517                 }
1518
1519                 if (gtk_text_iter_get_line_offset (&search) == 0)
1520                 {
1521                         if (!gtk_text_iter_backward_line (&search))
1522                                 break;
1523                 }
1524                 else
1525                 {
1526                         gtk_text_iter_set_line_offset (&search, 0);
1527                 }
1528         }
1529
1530         g_strfreev ((gchar **) lines);
1531
1532         return retval;
1533 }
1534
1535 gboolean
1536 empathy_window_get_is_visible (GtkWindow *window)
1537 {
1538         GdkWindowState  state;
1539         GdkWindow      *gdk_window;
1540
1541         g_return_val_if_fail (GTK_IS_WINDOW (window), FALSE);
1542
1543         gdk_window = gtk_widget_get_window (GTK_WIDGET (window));
1544         if (!gdk_window) {
1545                 return FALSE;
1546         }
1547
1548         state = gdk_window_get_state (gdk_window);
1549         if (state & (GDK_WINDOW_STATE_WITHDRAWN | GDK_WINDOW_STATE_ICONIFIED)) {
1550                 return FALSE;
1551         }
1552
1553         return TRUE;
1554 }
1555
1556 void
1557 empathy_window_iconify (GtkWindow *window, GtkStatusIcon *status_icon)
1558 {
1559         GdkRectangle  icon_location;
1560         gulong        data[4];
1561         Display      *dpy;
1562         GdkWindow    *gdk_window;
1563
1564         gtk_status_icon_get_geometry (status_icon, NULL, &icon_location, NULL);
1565         gdk_window = gtk_widget_get_window (GTK_WIDGET (window));
1566         dpy = GDK_WINDOW_XDISPLAY (gdk_window);
1567
1568         data[0] = icon_location.x;
1569         data[1] = icon_location.y;
1570         data[2] = icon_location.width;
1571         data[3] = icon_location.height;
1572
1573         XChangeProperty (dpy,
1574                          GDK_WINDOW_XID (gdk_window),
1575                          gdk_x11_get_xatom_by_name_for_display (
1576                                 gdk_window_get_display (gdk_window),
1577                          "_NET_WM_ICON_GEOMETRY"),
1578                          XA_CARDINAL, 32, PropModeReplace,
1579                          (guchar *)&data, 4);
1580
1581         gtk_window_set_skip_taskbar_hint (window, TRUE);
1582         gtk_window_iconify (window);
1583 }
1584
1585 /* Takes care of moving the window to the current workspace. */
1586 void
1587 empathy_window_present_with_time (GtkWindow *window,
1588                         guint32 timestamp)
1589 {
1590         GdkWindow *gdk_window;
1591
1592         g_return_if_fail (GTK_IS_WINDOW (window));
1593
1594         /* Move the window to the current workspace before trying to show it.
1595          * This is the behaviour people expect when clicking on the statusbar icon. */
1596         gdk_window = gtk_widget_get_window (GTK_WIDGET (window));
1597         if (gdk_window) {
1598                 gint x, y;
1599                 gint w, h;
1600
1601                 /* Has no effect if the WM has viewports, like compiz */
1602                 gdk_x11_window_move_to_current_desktop (gdk_window);
1603
1604                 /* If window is still off-screen, hide it to force it to
1605                  * reposition on the current workspace. */
1606                 gtk_window_get_position (window, &x, &y);
1607                 gtk_window_get_size (window, &w, &h);
1608                 if (!EMPATHY_RECT_IS_ON_SCREEN (x, y, w, h))
1609                         gtk_widget_hide (GTK_WIDGET (window));
1610         }
1611
1612         if (timestamp == GDK_CURRENT_TIME)
1613                 gtk_window_present (window);
1614         else
1615                 gtk_window_present_with_time (window, timestamp);
1616
1617         gtk_window_set_skip_taskbar_hint (window, FALSE);
1618         gtk_window_deiconify (window);
1619 }
1620
1621 void
1622 empathy_window_present (GtkWindow *window)
1623 {
1624   empathy_window_present_with_time (window, gtk_get_current_event_time ());
1625 }
1626
1627 GtkWindow *
1628 empathy_get_toplevel_window (GtkWidget *widget)
1629 {
1630         GtkWidget *toplevel;
1631
1632         g_return_val_if_fail (GTK_IS_WIDGET (widget), NULL);
1633
1634         toplevel = gtk_widget_get_toplevel (widget);
1635         if (GTK_IS_WINDOW (toplevel) &&
1636             gtk_widget_is_toplevel (toplevel)) {
1637                 return GTK_WINDOW (toplevel);
1638         }
1639
1640         return NULL;
1641 }
1642
1643 /** empathy_make_absolute_url_len:
1644  * @url: an url
1645  * @len: a length
1646  *
1647  * Same as #empathy_make_absolute_url but for a limited string length
1648  */
1649 gchar *
1650 empathy_make_absolute_url_len (const gchar *url,
1651                                guint len)
1652 {
1653         g_return_val_if_fail (url != NULL, NULL);
1654
1655         if (g_str_has_prefix (url, "ghelp:") ||
1656             g_str_has_prefix (url, "mailto:") ||
1657             strstr (url, ":/")) {
1658                 return g_strndup (url, len);
1659         }
1660
1661         if (strstr (url, "@")) {
1662                 return g_strdup_printf ("mailto:%.*s", len, url);
1663         }
1664
1665         return g_strdup_printf ("http://%.*s", len, url);
1666 }
1667
1668 /** empathy_make_absolute_url:
1669  * @url: an url
1670  *
1671  * The URL opening code can't handle schemeless strings, so we try to be
1672  * smart and add http if there is no scheme or doesn't look like a mail
1673  * address. This should work in most cases, and let us click on strings
1674  * like "www.gnome.org".
1675  *
1676  * Returns: a newly allocated url with proper mailto: or http:// prefix, use
1677  * g_free when your are done with it
1678  */
1679 gchar *
1680 empathy_make_absolute_url (const gchar *url)
1681 {
1682         return empathy_make_absolute_url_len (url, strlen (url));
1683 }
1684
1685 void
1686 empathy_url_show (GtkWidget *parent,
1687                   const char *url)
1688 {
1689         gchar  *real_url;
1690         GError *error = NULL;
1691
1692         g_return_if_fail (parent == NULL || GTK_IS_WIDGET (parent));
1693         g_return_if_fail (url != NULL);
1694
1695         real_url = empathy_make_absolute_url (url);
1696
1697         gtk_show_uri (parent ? gtk_widget_get_screen (parent) : NULL, real_url,
1698                       gtk_get_current_event_time (), &error);
1699
1700         if (error) {
1701                 GtkWidget *dialog;
1702
1703                 dialog = gtk_message_dialog_new (NULL, 0,
1704                                                  GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,
1705                                                  _("Unable to open URI"));
1706                 gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
1707                                                           "%s", error->message);
1708
1709                 g_signal_connect (dialog, "response",
1710                                   G_CALLBACK (gtk_widget_destroy),
1711                                   NULL);
1712                 gtk_window_present (GTK_WINDOW (dialog));
1713
1714                 g_clear_error (&error);
1715         }
1716
1717         g_free (real_url);
1718 }
1719
1720 void
1721 empathy_send_file (EmpathyContact *contact, GFile *file)
1722 {
1723         EmpathyFTFactory *factory;
1724         GtkRecentManager *manager;
1725         gchar *uri;
1726
1727         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1728         g_return_if_fail (G_IS_FILE (file));
1729
1730         factory = empathy_ft_factory_dup_singleton ();
1731
1732         empathy_ft_factory_new_transfer_outgoing (factory, contact, file);
1733
1734         uri = g_file_get_uri (file);
1735         manager = gtk_recent_manager_get_default ();
1736         gtk_recent_manager_add_item (manager, uri);
1737         g_free (uri);
1738
1739         g_object_unref (factory);
1740 }
1741
1742 void
1743 empathy_send_file_from_uri_list (EmpathyContact *contact, const gchar *uri_list)
1744 {
1745         const gchar *nl;
1746         GFile *file;
1747
1748         /* Only handle a single file for now.  It would be wicked cool to be
1749            able to do multiple files, offering to zip them or whatever like
1750            nautilus-sendto does.  Note that text/uri-list is defined to have
1751            each line terminated by \r\n, but we can be tolerant of applications
1752            that only use \n or don't terminate single-line entries.
1753         */
1754         nl = strstr (uri_list, "\r\n");
1755         if (!nl) {
1756                 nl = strchr (uri_list, '\n');
1757         }
1758         if (nl) {
1759                 gchar *uri = g_strndup (uri_list, nl - uri_list);
1760                 file = g_file_new_for_uri (uri);
1761                 g_free (uri);
1762         }
1763         else {
1764                 file = g_file_new_for_uri (uri_list);
1765         }
1766
1767         empathy_send_file (contact, file);
1768
1769         g_object_unref (file);
1770 }
1771
1772 static void
1773 file_manager_send_file_response_cb (GtkDialog      *widget,
1774                                     gint            response_id,
1775                                     EmpathyContact *contact)
1776 {
1777         GFile *file;
1778
1779         if (response_id == GTK_RESPONSE_OK) {
1780                 file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (widget));
1781
1782                 empathy_send_file (contact, file);
1783
1784                 g_object_unref (file);
1785         }
1786
1787         gtk_widget_destroy (GTK_WIDGET (widget));
1788 }
1789
1790 void
1791 empathy_send_file_with_file_chooser (EmpathyContact *contact)
1792 {
1793         GtkWidget               *widget;
1794         GtkWidget               *button;
1795
1796         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1797
1798         DEBUG ("Creating selection file chooser");
1799
1800         widget = gtk_file_chooser_dialog_new (_("Select a file"),
1801                                               NULL,
1802                                               GTK_FILE_CHOOSER_ACTION_OPEN,
1803                                               GTK_STOCK_CANCEL,
1804                                               GTK_RESPONSE_CANCEL,
1805                                               NULL);
1806
1807         /* send button */
1808         button = gtk_button_new_with_mnemonic (_("_Send"));
1809         gtk_button_set_image (GTK_BUTTON (button),
1810                 gtk_image_new_from_icon_name (EMPATHY_IMAGE_DOCUMENT_SEND,
1811                                               GTK_ICON_SIZE_BUTTON));
1812         gtk_widget_show (button);
1813         gtk_dialog_add_action_widget (GTK_DIALOG (widget), button,
1814                                       GTK_RESPONSE_OK);
1815         gtk_widget_set_can_default (button, TRUE);
1816         gtk_dialog_set_default_response (GTK_DIALOG (widget),
1817                                          GTK_RESPONSE_OK);
1818
1819         gtk_file_chooser_set_local_only (GTK_FILE_CHOOSER (widget), FALSE);
1820
1821         gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (widget),
1822                 g_get_home_dir ());
1823
1824         g_signal_connect (widget, "response",
1825                           G_CALLBACK (file_manager_send_file_response_cb),
1826                           contact);
1827
1828         gtk_widget_show (widget);
1829 }
1830
1831 static void
1832 file_manager_receive_file_response_cb (GtkDialog *dialog,
1833                                        GtkResponseType response,
1834                                        EmpathyFTHandler *handler)
1835 {
1836         EmpathyFTFactory *factory;
1837         GFile *file;
1838
1839         if (response == GTK_RESPONSE_OK) {
1840                 GFile *parent;
1841                 GFileInfo *info;
1842                 guint64 free_space, file_size;
1843                 GError *error = NULL;
1844
1845                 file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (dialog));
1846                 parent = g_file_get_parent (file);
1847                 info = g_file_query_filesystem_info (parent,
1848                                 G_FILE_ATTRIBUTE_FILESYSTEM_FREE,
1849                                 NULL, &error);
1850
1851                 g_object_unref (parent);
1852
1853                 if (error != NULL) {
1854                         g_warning ("Error: %s", error->message);
1855
1856                         g_object_unref (file);
1857                         return;
1858                 }
1859
1860                 free_space = g_file_info_get_attribute_uint64 (info,
1861                                 G_FILE_ATTRIBUTE_FILESYSTEM_FREE);
1862                 file_size = empathy_ft_handler_get_total_bytes (handler);
1863
1864                 g_object_unref (info);
1865
1866                 if (file_size > free_space) {
1867                         GtkWidget *message = gtk_message_dialog_new (
1868                                 GTK_WINDOW (dialog),
1869                                 GTK_DIALOG_MODAL,
1870                                 GTK_MESSAGE_ERROR,
1871                                 GTK_BUTTONS_CLOSE,
1872                                 _("Insufficient free space to save file"));
1873                         char *file_size_str, *free_space_str;
1874
1875                         file_size_str = g_format_size_for_display (file_size);
1876                         free_space_str = g_format_size_for_display (free_space);
1877
1878                         gtk_message_dialog_format_secondary_text (
1879                                 GTK_MESSAGE_DIALOG (message),
1880                                 _("%s of free space are required to save this "
1881                                   "file, but only %s is available. Please "
1882                                   "choose another location."),
1883                                 file_size_str, free_space_str);
1884
1885                         gtk_dialog_run (GTK_DIALOG (message));
1886
1887                         g_free (file_size_str);
1888                         g_free (free_space_str);
1889                         gtk_widget_destroy (message);
1890
1891                         g_object_unref (file);
1892
1893                         return;
1894                 }
1895
1896                 factory = empathy_ft_factory_dup_singleton ();
1897
1898                 empathy_ft_factory_set_destination_for_incoming_handler (
1899                                 factory, handler, file);
1900
1901                 g_object_unref (factory);
1902                 g_object_unref (file);
1903         } else {
1904                 /* unref the handler, as we dismissed the file chooser,
1905                  * and refused the transfer.
1906                  */
1907                 g_object_unref (handler);
1908         }
1909
1910         gtk_widget_destroy (GTK_WIDGET (dialog));
1911 }
1912
1913 void
1914 empathy_receive_file_with_file_chooser (EmpathyFTHandler *handler)
1915 {
1916         GtkWidget *widget;
1917         const gchar *dir;
1918         EmpathyContact *contact;
1919         gchar *title;
1920
1921         contact = empathy_ft_handler_get_contact (handler);
1922         g_assert (contact != NULL);
1923
1924         title = g_strdup_printf (_("Incoming file from %s"),
1925                 empathy_contact_get_alias (contact));
1926
1927         widget = gtk_file_chooser_dialog_new (title,
1928                                               NULL,
1929                                               GTK_FILE_CHOOSER_ACTION_SAVE,
1930                                               GTK_STOCK_CANCEL,
1931                                               GTK_RESPONSE_CANCEL,
1932                                               GTK_STOCK_SAVE,
1933                                               GTK_RESPONSE_OK,
1934                                               NULL);
1935         gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (widget),
1936                 empathy_ft_handler_get_filename (handler));
1937         gtk_file_chooser_set_do_overwrite_confirmation
1938                 (GTK_FILE_CHOOSER (widget), TRUE);
1939
1940         dir = g_get_user_special_dir (G_USER_DIRECTORY_DOWNLOAD);
1941         if (dir == NULL)
1942                 /* Fallback to $HOME if $XDG_DOWNLOAD_DIR is not set */
1943                 dir = g_get_home_dir ();
1944
1945         gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (widget), dir);
1946
1947         g_signal_connect (widget, "response",
1948                 G_CALLBACK (file_manager_receive_file_response_cb), handler);
1949
1950         gtk_widget_show (widget);
1951         g_free (title);
1952 }
1953
1954 void
1955 empathy_make_color_whiter (GdkRGBA *color)
1956 {
1957         const GdkRGBA white = { 1.0, 1.0, 1.0, 1.0 };
1958
1959         color->red = (color->red + white.red) / 2;
1960         color->green = (color->green + white.green) / 2;
1961         color->blue = (color->blue + white.blue) / 2;
1962 }
1963
1964 static void
1965 menu_deactivate_cb (GtkMenu *menu,
1966         gpointer user_data)
1967 {
1968         /* FIXME: we shouldn't have to disconnect the signal (bgo #641327) */
1969         g_signal_handlers_disconnect_by_func (menu,
1970                      menu_deactivate_cb, user_data);
1971
1972         gtk_menu_detach (menu);
1973 }
1974
1975 /* Convenient function to create a GtkMenu attached to @attach_to and detach
1976  * it when the menu is not displayed any more. This is useful when creating a
1977  * context menu that we want to get rid as soon as it as been displayed. */
1978 GtkWidget *
1979 empathy_context_menu_new (GtkWidget *attach_to)
1980 {
1981         GtkWidget *menu;
1982
1983         menu = gtk_menu_new ();
1984
1985         gtk_menu_attach_to_widget (GTK_MENU (menu), attach_to, NULL);
1986
1987         /* menu is initially unowned but gtk_menu_attach_to_widget () taked its
1988          * floating ref. We can either wait that @attach_to releases its ref when
1989          * it will be destroyed (when leaving Empathy most of the time) or explicitely
1990          * detach the menu when it's not displayed any more.
1991          * We go for the latter as we don't want to keep useless menus in memory
1992          * during the whole lifetime of Empathy. */
1993         g_signal_connect (menu, "deactivate", G_CALLBACK (menu_deactivate_cb), NULL);
1994
1995         return menu;
1996 }