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