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