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