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