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