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