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