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