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