]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-ui-utils.c
Use foo[1] rather than *(foo + 1)
[empathy.git] / libempathy-gtk / empathy-ui-utils.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  * Copyright (C) 2002-2007 Imendio AB
4  * Copyright (C) 2007-2008 Collabora Ltd.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation; either version 2 of the
9  * License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public
17  * License along with this program; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  * 
21  * Authors: Mikael Hallendal <micke@imendio.com>
22  *          Richard Hult <richard@imendio.com>
23  *          Martyn Russell <martyn@imendio.com>
24  *          Xavier Claessens <xclaesse@gmail.com>
25  * 
26  *          Part of this file is copied from GtkSourceView (gtksourceiter.c):
27  *          Paolo Maggi
28  *          Jeroen Zwartepoorte
29  */
30
31 #include <config.h>
32
33 #include <string.h>
34 #include <X11/Xatom.h>
35 #include <gdk/gdkx.h>
36 #include <glib/gi18n.h>
37 #include <gtk/gtk.h>
38 #include <gio/gio.h>
39 #include <glade/glade.h>
40
41 #include <libmissioncontrol/mc-profile.h>
42
43 #include "empathy-ui-utils.h"
44 #include "empathy-images.h"
45
46 #define DEBUG_FLAG EMPATHY_DEBUG_OTHER
47 #include <libempathy/empathy-debug.h>
48
49 struct SizeData {
50         gint     width;
51         gint     height;
52         gboolean preserve_aspect_ratio;
53 };
54
55 static GladeXML *
56 get_glade_file (const gchar *filename,
57                 const gchar *root,
58                 const gchar *domain,
59                 const gchar *first_required_widget,
60                 va_list      args)
61 {
62         GladeXML   *gui;
63         const char *name;
64         GtkWidget **widget_ptr;
65
66         DEBUG ("Loading glade file %s", filename);
67
68         gui = glade_xml_new (filename, root, domain);
69
70         if (!gui) {
71                 g_warning ("Couldn't find necessary glade file '%s'", filename);
72         }
73
74         for (name = first_required_widget; name; name = va_arg (args, char *)) {
75                 widget_ptr = va_arg (args, void *);
76
77                 *widget_ptr = glade_xml_get_widget (gui, name);
78
79                 if (!*widget_ptr) {
80                         g_warning ("Glade file '%s' is missing widget '%s'.",
81                                    filename, name);
82                         continue;
83                 }
84         }
85
86         return gui;
87 }
88
89 void
90 empathy_glade_get_file_simple (const gchar *filename,
91                               const gchar *root,
92                               const gchar *domain,
93                               const gchar *first_required_widget, ...)
94 {
95         va_list   args;
96         GladeXML *gui;
97
98         va_start (args, first_required_widget);
99
100         gui = get_glade_file (filename,
101                               root,
102                               domain,
103                               first_required_widget,
104                               args);
105
106         va_end (args);
107
108         if (gui) {
109                 g_object_unref (gui);
110         }
111 }
112
113 GladeXML *
114 empathy_glade_get_file (const gchar *filename,
115                        const gchar *root,
116                        const gchar *domain,
117                        const gchar *first_required_widget, ...)
118 {
119         va_list   args;
120         GladeXML *gui;
121
122         va_start (args, first_required_widget);
123
124         gui = get_glade_file (filename,
125                               root,
126                               domain,
127                               first_required_widget,
128                               args);
129
130         va_end (args);
131
132         if (!gui) {
133                 return NULL;
134         }
135
136         return gui;
137 }
138
139 void
140 empathy_glade_connect (GladeXML *gui,
141                       gpointer  user_data,
142                       gchar     *first_widget, ...)
143 {
144         va_list      args;
145         const gchar *name;
146         const gchar *signal;
147         GtkWidget   *widget;
148         gpointer    *callback;
149
150         va_start (args, first_widget);
151
152         for (name = first_widget; name; name = va_arg (args, char *)) {
153                 signal = va_arg (args, void *);
154                 callback = va_arg (args, void *);
155
156                 widget = glade_xml_get_widget (gui, name);
157                 if (!widget) {
158                         g_warning ("Glade file is missing widget '%s', aborting",
159                                    name);
160                         continue;
161                 }
162
163                 g_signal_connect (widget,
164                                   signal,
165                                   G_CALLBACK (callback),
166                                   user_data);
167         }
168
169         va_end (args);
170 }
171
172 void
173 empathy_glade_setup_size_group (GladeXML         *gui,
174                                GtkSizeGroupMode  mode,
175                                gchar            *first_widget, ...)
176 {
177         va_list       args;
178         GtkWidget    *widget;
179         GtkSizeGroup *size_group;
180         const gchar  *name;
181
182         va_start (args, first_widget);
183
184         size_group = gtk_size_group_new (mode);
185
186         for (name = first_widget; name; name = va_arg (args, char *)) {
187                 widget = glade_xml_get_widget (gui, name);
188                 if (!widget) {
189                         g_warning ("Glade file is missing widget '%s'", name);
190                         continue;
191                 }
192
193                 gtk_size_group_add_widget (size_group, widget);
194         }
195
196         g_object_unref (size_group);
197
198         va_end (args);
199 }
200
201 const gchar *
202 empathy_icon_name_from_account (McAccount *account)
203 {
204         McProfile *profile;
205
206         profile = mc_account_get_profile (account);
207
208         return mc_profile_get_icon_name (profile);
209 }
210
211 const gchar *
212 empathy_icon_name_for_presence (McPresence presence)
213 {
214         switch (presence) {
215         case MC_PRESENCE_AVAILABLE:
216                 return EMPATHY_IMAGE_AVAILABLE;
217         case MC_PRESENCE_DO_NOT_DISTURB:
218                 return EMPATHY_IMAGE_BUSY;
219         case MC_PRESENCE_AWAY:
220                 return EMPATHY_IMAGE_AWAY;
221         case MC_PRESENCE_EXTENDED_AWAY:
222                 return EMPATHY_IMAGE_EXT_AWAY;
223         case MC_PRESENCE_HIDDEN:
224                 return EMPATHY_IMAGE_HIDDEN;
225         case MC_PRESENCE_OFFLINE:
226         case MC_PRESENCE_UNSET:
227                 return EMPATHY_IMAGE_OFFLINE;
228         default:
229                 g_assert_not_reached ();
230         }
231
232         return NULL;
233 }
234
235 const gchar *
236 empathy_icon_name_for_contact (EmpathyContact *contact)
237 {
238         McPresence presence;
239
240         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact),
241                               EMPATHY_IMAGE_OFFLINE);
242
243         presence = empathy_contact_get_presence (contact);
244         return empathy_icon_name_for_presence (presence);
245 }
246
247 GdkPixbuf *
248 empathy_pixbuf_from_data (gchar  *data,
249                           gsize   data_size,
250                           gchar **mime_type)
251 {
252         GdkPixbufLoader *loader;
253         GdkPixbufFormat *format;
254         GdkPixbuf       *pixbuf = NULL;
255         gchar          **mime_types;
256         GError          *error = NULL;
257
258         if (!data) {
259                 return NULL;
260         }
261
262         loader = gdk_pixbuf_loader_new ();
263         if (!gdk_pixbuf_loader_write (loader, data, data_size, &error)) {
264                 DEBUG ("Failed to write to pixbuf loader: %s",
265                         error ? error->message : "No error given");
266                 goto out;
267         }
268         if (!gdk_pixbuf_loader_close (loader, &error)) {
269                 DEBUG ("Failed to close pixbuf loader: %s",
270                         error ? error->message : "No error given");
271                 goto out;
272         }
273
274         pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
275         if (pixbuf) {
276                 g_object_ref (pixbuf);
277
278                 if (mime_type != NULL) {
279                         format = gdk_pixbuf_loader_get_format (loader);
280                         mime_types = gdk_pixbuf_format_get_mime_types (format);
281
282                         *mime_type = g_strdup (*mime_types);
283                         if (mime_types[1] != NULL) {
284                                 DEBUG ("Loader supports more than one mime "
285                                         "type! Picking the first one, %s",
286                                         *mime_type);
287                         }
288                         g_strfreev (mime_types);
289                 }
290         }
291
292 out:
293         g_clear_error (&error);
294         g_object_unref (loader);
295
296         return pixbuf;
297 }
298
299 static void
300 pixbuf_from_avatar_size_prepared_cb (GdkPixbufLoader *loader,
301                                      int              width,
302                                      int              height,
303                                      struct SizeData *data)
304 {
305         g_return_if_fail (width > 0 && height > 0);
306
307         if (data->preserve_aspect_ratio && (data->width > 0 || data->height > 0)) {
308                 if (width < data->width && height < data->height) {
309                         width = width;
310                         height = height;
311                 }
312
313                 if (data->width < 0) {
314                         width = width * (double) data->height / (gdouble) height;
315                         height = data->height;
316                 } else if (data->height < 0) {
317                         height = height * (double) data->width / (double) width;
318                         width = data->width;
319                 } else if ((double) height * (double) data->width >
320                            (double) width * (double) data->height) {
321                         width = 0.5 + (double) width * (double) data->height / (double) height;
322                         height = data->height;
323                 } else {
324                         height = 0.5 + (double) height * (double) data->width / (double) width;
325                         width = data->width;
326                 }
327         } else {
328                 if (data->width > 0) {
329                         width = data->width;
330                 }
331
332                 if (data->height > 0) {
333                         height = data->height;
334                 }
335         }
336
337         gdk_pixbuf_loader_set_size (loader, width, height);
338 }
339
340 static void
341 empathy_avatar_pixbuf_roundify (GdkPixbuf *pixbuf)
342 {
343         gint width, height, rowstride;
344         guchar *pixels;
345
346         width = gdk_pixbuf_get_width (pixbuf);
347         height = gdk_pixbuf_get_height (pixbuf);
348         rowstride = gdk_pixbuf_get_rowstride (pixbuf);
349         pixels = gdk_pixbuf_get_pixels (pixbuf);
350
351         if (width < 6 || height < 6) {
352                 return;
353         }
354
355         /* Top left */
356         pixels[3] = 0;
357         pixels[7] = 0x80;
358         pixels[11] = 0xC0;
359         pixels[rowstride + 3] = 0x80;
360         pixels[rowstride * 2 + 3] = 0xC0;
361
362         /* Top right */
363         pixels[width * 4 - 1] = 0;
364         pixels[width * 4 - 5] = 0x80;
365         pixels[width * 4 - 9] = 0xC0;
366         pixels[rowstride + (width * 4) - 1] = 0x80;
367         pixels[(2 * rowstride) + (width * 4) - 1] = 0xC0;
368
369         /* Bottom left */
370         pixels[(height - 1) * rowstride + 3] = 0;
371         pixels[(height - 1) * rowstride + 7] = 0x80;
372         pixels[(height - 1) * rowstride + 11] = 0xC0;
373         pixels[(height - 2) * rowstride + 3] = 0x80;
374         pixels[(height - 3) * rowstride + 3] = 0xC0;
375
376         /* Bottom right */
377         pixels[height * rowstride - 1] = 0;
378         pixels[(height - 1) * rowstride - 1] = 0x80;
379         pixels[(height - 2) * rowstride - 1] = 0xC0;
380         pixels[height * rowstride - 5] = 0x80;
381         pixels[height * rowstride - 9] = 0xC0;
382 }
383
384 static gboolean
385 empathy_gdk_pixbuf_is_opaque (GdkPixbuf *pixbuf)
386 {
387         gint width, height, rowstride, i;
388         guchar *pixels;
389         guchar *row;
390
391         width = gdk_pixbuf_get_width (pixbuf);
392         height = gdk_pixbuf_get_height (pixbuf);
393         rowstride = gdk_pixbuf_get_rowstride (pixbuf);
394         pixels = gdk_pixbuf_get_pixels (pixbuf);
395
396         row = pixels;
397         for (i = 3; i < rowstride; i+=4) {
398                 if (row[i] < 0xfe) {
399                         return FALSE;
400                 }
401         }
402
403         for (i = 1; i < height - 1; i++) {
404                 row = pixels + (i*rowstride);
405                 if (row[3] < 0xfe || row[rowstride-1] < 0xfe) {
406                         return FALSE;
407                 }
408         }
409
410         row = pixels + ((height-1) * rowstride);
411         for (i = 3; i < rowstride; i+=4) {
412                 if (row[i] < 0xfe) {
413                         return FALSE;
414                 }
415         }
416
417         return TRUE;
418 }
419
420 GdkPixbuf *
421 empathy_pixbuf_from_avatar_scaled (EmpathyAvatar *avatar,
422                                   gint          width,
423                                   gint          height)
424 {
425         GdkPixbuf        *pixbuf;
426         GdkPixbufLoader  *loader;
427         struct SizeData   data;
428         GError           *error = NULL;
429
430         if (!avatar) {
431                 return NULL;
432         }
433
434         data.width = width;
435         data.height = height;
436         data.preserve_aspect_ratio = TRUE;
437
438         loader = gdk_pixbuf_loader_new ();
439
440         g_signal_connect (loader, "size-prepared",
441                           G_CALLBACK (pixbuf_from_avatar_size_prepared_cb),
442                           &data);
443
444         if (!gdk_pixbuf_loader_write (loader, avatar->data, avatar->len, &error)) {
445                 g_warning ("Couldn't write avatar image:%p with "
446                            "length:%" G_GSIZE_FORMAT " to pixbuf loader: %s",
447                            avatar->data, avatar->len, error->message);
448                 g_error_free (error);
449                 return NULL;
450         }
451
452         gdk_pixbuf_loader_close (loader, NULL);
453
454         pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
455         if (!gdk_pixbuf_get_has_alpha (pixbuf)) {
456                 GdkPixbuf *rounded_pixbuf;
457
458                 rounded_pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8,
459                                                  gdk_pixbuf_get_width (pixbuf),
460                                                  gdk_pixbuf_get_height (pixbuf));
461                 gdk_pixbuf_copy_area (pixbuf, 0, 0,
462                                       gdk_pixbuf_get_width (pixbuf),
463                                       gdk_pixbuf_get_height (pixbuf),
464                                       rounded_pixbuf,
465                                       0, 0);
466                 pixbuf = rounded_pixbuf;
467         } else {
468                 g_object_ref (pixbuf);
469         }
470
471         if (empathy_gdk_pixbuf_is_opaque (pixbuf)) {
472                 empathy_avatar_pixbuf_roundify (pixbuf);
473         }
474
475         g_object_unref (loader);
476
477         return pixbuf;
478 }
479
480 GdkPixbuf *
481 empathy_pixbuf_avatar_from_contact_scaled (EmpathyContact *contact,
482                                           gint           width,
483                                           gint           height)
484 {
485         EmpathyAvatar *avatar;
486
487         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
488
489         avatar = empathy_contact_get_avatar (contact);
490
491         return empathy_pixbuf_from_avatar_scaled (avatar, width, height);
492 }
493
494 GdkPixbuf *
495 empathy_pixbuf_scale_down_if_necessary (GdkPixbuf *pixbuf, gint max_size)
496 {
497         gint      width, height;
498         gdouble   factor;
499
500         width = gdk_pixbuf_get_width (pixbuf);
501         height = gdk_pixbuf_get_height (pixbuf);
502
503         if (width > 0 && (width > max_size || height > max_size)) {
504                 factor = (gdouble) max_size / MAX (width, height);
505
506                 width = width * factor;
507                 height = height * factor;
508
509                 return gdk_pixbuf_scale_simple (pixbuf,
510                                                 width, height,
511                                                 GDK_INTERP_HYPER);
512         }
513
514         return g_object_ref (pixbuf);
515 }
516
517 GdkPixbuf *
518 empathy_pixbuf_from_icon_name (const gchar *icon_name,
519                               GtkIconSize  icon_size)
520 {
521         GtkIconTheme  *theme;
522         GdkPixbuf     *pixbuf = NULL;
523         GError        *error = NULL;
524         gint           w, h;
525         gint           size = 48;
526
527         if (!icon_name) {
528                 return NULL;
529         }
530
531         theme = gtk_icon_theme_get_default ();
532
533         if (gtk_icon_size_lookup (icon_size, &w, &h)) {
534                 size = (w + h) / 2;
535         }
536
537         pixbuf = gtk_icon_theme_load_icon (theme,
538                                            icon_name,
539                                            size,
540                                            0,
541                                            &error);
542         if (error) {
543                 DEBUG ("Error loading icon: %s", error->message);
544                 g_clear_error (&error);
545         }
546
547         return pixbuf;
548 }
549
550 /* Stolen from GtkSourceView, hence the weird intendation. Please keep it like
551  * that to make it easier to apply changes from the original code.
552  */
553 #define GTK_TEXT_UNKNOWN_CHAR 0xFFFC
554
555 /* this function acts like g_utf8_offset_to_pointer() except that if it finds a
556  * decomposable character it consumes the decomposition length from the given
557  * offset.  So it's useful when the offset was calculated for the normalized
558  * version of str, but we need a pointer to str itself. */
559 static const gchar *
560 pointer_from_offset_skipping_decomp (const gchar *str, gint offset)
561 {
562         gchar *casefold, *normal;
563         const gchar *p, *q;
564
565         p = str;
566         while (offset > 0)
567         {
568                 q = g_utf8_next_char (p);
569                 casefold = g_utf8_casefold (p, q - p);
570                 normal = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
571                 offset -= g_utf8_strlen (normal, -1);
572                 g_free (casefold);
573                 g_free (normal);
574                 p = q;
575         }
576         return p;
577 }
578
579 static const gchar *
580 g_utf8_strcasestr (const gchar *haystack, const gchar *needle)
581 {
582         gsize needle_len;
583         gsize haystack_len;
584         const gchar *ret = NULL;
585         gchar *p;
586         gchar *casefold;
587         gchar *caseless_haystack;
588         gint i;
589
590         g_return_val_if_fail (haystack != NULL, NULL);
591         g_return_val_if_fail (needle != NULL, NULL);
592
593         casefold = g_utf8_casefold (haystack, -1);
594         caseless_haystack = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
595         g_free (casefold);
596
597         needle_len = g_utf8_strlen (needle, -1);
598         haystack_len = g_utf8_strlen (caseless_haystack, -1);
599
600         if (needle_len == 0)
601         {
602                 ret = (gchar *)haystack;
603                 goto finally_1;
604         }
605
606         if (haystack_len < needle_len)
607         {
608                 ret = NULL;
609                 goto finally_1;
610         }
611
612         p = (gchar*)caseless_haystack;
613         needle_len = strlen (needle);
614         i = 0;
615
616         while (*p)
617         {
618                 if ((strncmp (p, needle, needle_len) == 0))
619                 {
620                         ret = pointer_from_offset_skipping_decomp (haystack, i);
621                         goto finally_1;
622                 }
623
624                 p = g_utf8_next_char (p);
625                 i++;
626         }
627
628 finally_1:
629         g_free (caseless_haystack);
630
631         return ret;
632 }
633
634 static gboolean
635 g_utf8_caselessnmatch (const char *s1, const char *s2,
636                        gssize n1, gssize n2)
637 {
638         gchar *casefold;
639         gchar *normalized_s1;
640         gchar *normalized_s2;
641         gint len_s1;
642         gint len_s2;
643         gboolean ret = FALSE;
644
645         g_return_val_if_fail (s1 != NULL, FALSE);
646         g_return_val_if_fail (s2 != NULL, FALSE);
647         g_return_val_if_fail (n1 > 0, FALSE);
648         g_return_val_if_fail (n2 > 0, FALSE);
649
650         casefold = g_utf8_casefold (s1, n1);
651         normalized_s1 = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
652         g_free (casefold);
653
654         casefold = g_utf8_casefold (s2, n2);
655         normalized_s2 = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
656         g_free (casefold);
657
658         len_s1 = strlen (normalized_s1);
659         len_s2 = strlen (normalized_s2);
660
661         if (len_s1 < len_s2)
662                 goto finally_2;
663
664         ret = (strncmp (normalized_s1, normalized_s2, len_s2) == 0);
665
666 finally_2:
667         g_free (normalized_s1);
668         g_free (normalized_s2);
669
670         return ret;
671 }
672
673 static void
674 forward_chars_with_skipping (GtkTextIter *iter,
675                              gint         count,
676                              gboolean     skip_invisible,
677                              gboolean     skip_nontext,
678                              gboolean     skip_decomp)
679 {
680         gint i;
681
682         g_return_if_fail (count >= 0);
683
684         i = count;
685
686         while (i > 0)
687         {
688                 gboolean ignored = FALSE;
689
690                 /* minimal workaround to avoid the infinite loop of bug #168247.
691                  * It doesn't fix the problemjust the symptom...
692                  */
693                 if (gtk_text_iter_is_end (iter))
694                         return;
695
696                 if (skip_nontext && gtk_text_iter_get_char (iter) == GTK_TEXT_UNKNOWN_CHAR)
697                         ignored = TRUE;
698
699                 if (!ignored && skip_invisible &&
700                     /* _gtk_text_btree_char_is_invisible (iter)*/ FALSE)
701                         ignored = TRUE;
702
703                 if (!ignored && skip_decomp)
704                 {
705                         /* being UTF8 correct sucks; this accounts for extra
706                            offsets coming from canonical decompositions of
707                            UTF8 characters (e.g. accented characters) which
708                            g_utf8_normalize() performs */
709                         gchar *normal;
710                         gchar buffer[6];
711                         gint buffer_len;
712
713                         buffer_len = g_unichar_to_utf8 (gtk_text_iter_get_char (iter), buffer);
714                         normal = g_utf8_normalize (buffer, buffer_len, G_NORMALIZE_NFD);
715                         i -= (g_utf8_strlen (normal, -1) - 1);
716                         g_free (normal);
717                 }
718
719                 gtk_text_iter_forward_char (iter);
720
721                 if (!ignored)
722                         --i;
723         }
724 }
725
726 static gboolean
727 lines_match (const GtkTextIter *start,
728              const gchar      **lines,
729              gboolean           visible_only,
730              gboolean           slice,
731              GtkTextIter       *match_start,
732              GtkTextIter       *match_end)
733 {
734         GtkTextIter next;
735         gchar *line_text;
736         const gchar *found;
737         gint offset;
738
739         if (*lines == NULL || **lines == '\0')
740         {
741                 if (match_start)
742                         *match_start = *start;
743                 if (match_end)
744                         *match_end = *start;
745                 return TRUE;
746         }
747
748         next = *start;
749         gtk_text_iter_forward_line (&next);
750
751         /* No more text in buffer, but *lines is nonempty */
752         if (gtk_text_iter_equal (start, &next))
753                 return FALSE;
754
755         if (slice)
756         {
757                 if (visible_only)
758                         line_text = gtk_text_iter_get_visible_slice (start, &next);
759                 else
760                         line_text = gtk_text_iter_get_slice (start, &next);
761         }
762         else
763         {
764                 if (visible_only)
765                         line_text = gtk_text_iter_get_visible_text (start, &next);
766                 else
767                         line_text = gtk_text_iter_get_text (start, &next);
768         }
769
770         if (match_start) /* if this is the first line we're matching */
771         {
772                 found = g_utf8_strcasestr (line_text, *lines);
773         }
774         else
775         {
776                 /* If it's not the first line, we have to match from the
777                  * start of the line.
778                  */
779                 if (g_utf8_caselessnmatch (line_text, *lines, strlen (line_text),
780                                            strlen (*lines)))
781                         found = line_text;
782                 else
783                         found = NULL;
784         }
785
786         if (found == NULL)
787         {
788                 g_free (line_text);
789                 return FALSE;
790         }
791
792         /* Get offset to start of search string */
793         offset = g_utf8_strlen (line_text, found - line_text);
794
795         next = *start;
796
797         /* If match start needs to be returned, set it to the
798          * start of the search string.
799          */
800         forward_chars_with_skipping (&next, offset, visible_only, !slice, FALSE);
801         if (match_start)
802         {
803                 *match_start = next;
804         }
805
806         /* Go to end of search string */
807         forward_chars_with_skipping (&next, g_utf8_strlen (*lines, -1), visible_only, !slice, TRUE);
808
809         g_free (line_text);
810
811         ++lines;
812
813         if (match_end)
814                 *match_end = next;
815
816         /* pass NULL for match_start, since we don't need to find the
817          * start again.
818          */
819         return lines_match (&next, lines, visible_only, slice, NULL, match_end);
820 }
821
822 /* strsplit () that retains the delimiter as part of the string. */
823 static gchar **
824 strbreakup (const char *string,
825             const char *delimiter,
826             gint        max_tokens)
827 {
828         GSList *string_list = NULL, *slist;
829         gchar **str_array, *s, *casefold, *new_string;
830         guint i, n = 1;
831
832         g_return_val_if_fail (string != NULL, NULL);
833         g_return_val_if_fail (delimiter != NULL, NULL);
834
835         if (max_tokens < 1)
836                 max_tokens = G_MAXINT;
837
838         s = strstr (string, delimiter);
839         if (s)
840         {
841                 guint delimiter_len = strlen (delimiter);
842
843                 do
844                 {
845                         guint len;
846
847                         len = s - string + delimiter_len;
848                         new_string = g_new (gchar, len + 1);
849                         strncpy (new_string, string, len);
850                         new_string[len] = 0;
851                         casefold = g_utf8_casefold (new_string, -1);
852                         g_free (new_string);
853                         new_string = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
854                         g_free (casefold);
855                         string_list = g_slist_prepend (string_list, new_string);
856                         n++;
857                         string = s + delimiter_len;
858                         s = strstr (string, delimiter);
859                 } while (--max_tokens && s);
860         }
861
862         if (*string)
863         {
864                 n++;
865                 casefold = g_utf8_casefold (string, -1);
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         }
870
871         str_array = g_new (gchar*, n);
872
873         i = n - 1;
874
875         str_array[i--] = NULL;
876         for (slist = string_list; slist; slist = slist->next)
877                 str_array[i--] = slist->data;
878
879         g_slist_free (string_list);
880
881         return str_array;
882 }
883
884 gboolean
885 empathy_text_iter_forward_search (const GtkTextIter   *iter,
886                                  const gchar         *str,
887                                  GtkTextIter         *match_start,
888                                  GtkTextIter         *match_end,
889                                  const GtkTextIter   *limit)
890 {
891         gchar **lines = NULL;
892         GtkTextIter match;
893         gboolean retval = FALSE;
894         GtkTextIter search;
895         gboolean visible_only;
896         gboolean slice;
897
898         g_return_val_if_fail (iter != NULL, FALSE);
899         g_return_val_if_fail (str != NULL, FALSE);
900
901         if (limit && gtk_text_iter_compare (iter, limit) >= 0)
902                 return FALSE;
903
904         if (*str == '\0') {
905                 /* If we can move one char, return the empty string there */
906                 match = *iter;
907
908                 if (gtk_text_iter_forward_char (&match)) {
909                         if (limit && gtk_text_iter_equal (&match, limit)) {
910                                 return FALSE;
911                         }
912
913                         if (match_start) {
914                                 *match_start = match;
915                         }
916                         if (match_end) {
917                                 *match_end = match;
918                         }
919                         return TRUE;
920                 } else {
921                         return FALSE;
922                 }
923         }
924
925         visible_only = TRUE;
926         slice = FALSE;
927
928         /* locate all lines */
929         lines = strbreakup (str, "\n", -1);
930
931         search = *iter;
932
933         do {
934                 /* This loop has an inefficient worst-case, where
935                  * gtk_text_iter_get_text () is called repeatedly on
936                  * a single line.
937                  */
938                 GtkTextIter end;
939
940                 if (limit && gtk_text_iter_compare (&search, limit) >= 0) {
941                         break;
942                 }
943
944                 if (lines_match (&search, (const gchar**)lines,
945                                  visible_only, slice, &match, &end)) {
946                         if (limit == NULL ||
947                             (limit && gtk_text_iter_compare (&end, limit) <= 0)) {
948                                 retval = TRUE;
949
950                                 if (match_start) {
951                                         *match_start = match;
952                                 }
953                                 if (match_end) {
954                                         *match_end = end;
955                                 }
956                         }
957                         break;
958                 }
959         } while (gtk_text_iter_forward_line (&search));
960
961         g_strfreev ((gchar**)lines);
962
963         return retval;
964 }
965
966 static const gchar *
967 g_utf8_strrcasestr (const gchar *haystack, const gchar *needle)
968 {
969         gsize needle_len;
970         gsize haystack_len;
971         const gchar *ret = NULL;
972         gchar *p;
973         gchar *casefold;
974         gchar *caseless_haystack;
975         gint i;
976
977         g_return_val_if_fail (haystack != NULL, NULL);
978         g_return_val_if_fail (needle != NULL, NULL);
979
980         casefold = g_utf8_casefold (haystack, -1);
981         caseless_haystack = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
982         g_free (casefold);
983
984         needle_len = g_utf8_strlen (needle, -1);
985         haystack_len = g_utf8_strlen (caseless_haystack, -1);
986
987         if (needle_len == 0)
988         {
989                 ret = (gchar *)haystack;
990                 goto finally_1;
991         }
992
993         if (haystack_len < needle_len)
994         {
995                 ret = NULL;
996                 goto finally_1;
997         }
998
999         i = haystack_len - needle_len;
1000         p = g_utf8_offset_to_pointer (caseless_haystack, i);
1001         needle_len = strlen (needle);
1002
1003         while (p >= caseless_haystack)
1004         {
1005                 if (strncmp (p, needle, needle_len) == 0)
1006                 {
1007                         ret = pointer_from_offset_skipping_decomp (haystack, i);
1008                         goto finally_1;
1009                 }
1010
1011                 p = g_utf8_prev_char (p);
1012                 i--;
1013         }
1014
1015 finally_1:
1016         g_free (caseless_haystack);
1017
1018         return ret;
1019 }
1020
1021 static gboolean
1022 backward_lines_match (const GtkTextIter *start,
1023                       const gchar      **lines,
1024                       gboolean           visible_only,
1025                       gboolean           slice,
1026                       GtkTextIter       *match_start,
1027                       GtkTextIter       *match_end)
1028 {
1029         GtkTextIter line, next;
1030         gchar *line_text;
1031         const gchar *found;
1032         gint offset;
1033
1034         if (*lines == NULL || **lines == '\0')
1035         {
1036                 if (match_start)
1037                         *match_start = *start;
1038                 if (match_end)
1039                         *match_end = *start;
1040                 return TRUE;
1041         }
1042
1043         line = next = *start;
1044         if (gtk_text_iter_get_line_offset (&next) == 0)
1045         {
1046                 if (!gtk_text_iter_backward_line (&next))
1047                         return FALSE;
1048         }
1049         else
1050                 gtk_text_iter_set_line_offset (&next, 0);
1051
1052         if (slice)
1053         {
1054                 if (visible_only)
1055                         line_text = gtk_text_iter_get_visible_slice (&next, &line);
1056                 else
1057                         line_text = gtk_text_iter_get_slice (&next, &line);
1058         }
1059         else
1060         {
1061                 if (visible_only)
1062                         line_text = gtk_text_iter_get_visible_text (&next, &line);
1063                 else
1064                         line_text = gtk_text_iter_get_text (&next, &line);
1065         }
1066
1067         if (match_start) /* if this is the first line we're matching */
1068         {
1069                 found = g_utf8_strrcasestr (line_text, *lines);
1070         }
1071         else
1072         {
1073                 /* If it's not the first line, we have to match from the
1074                  * start of the line.
1075                  */
1076                 if (g_utf8_caselessnmatch (line_text, *lines, strlen (line_text),
1077                                            strlen (*lines)))
1078                         found = line_text;
1079                 else
1080                         found = NULL;
1081         }
1082
1083         if (found == NULL)
1084         {
1085                 g_free (line_text);
1086                 return FALSE;
1087         }
1088
1089         /* Get offset to start of search string */
1090         offset = g_utf8_strlen (line_text, found - line_text);
1091
1092         forward_chars_with_skipping (&next, offset, visible_only, !slice, FALSE);
1093
1094         /* If match start needs to be returned, set it to the
1095          * start of the search string.
1096          */
1097         if (match_start)
1098         {
1099                 *match_start = next;
1100         }
1101
1102         /* Go to end of search string */
1103         forward_chars_with_skipping (&next, g_utf8_strlen (*lines, -1), visible_only, !slice, TRUE);
1104
1105         g_free (line_text);
1106
1107         ++lines;
1108
1109         if (match_end)
1110                 *match_end = next;
1111
1112         /* try to match the rest of the lines forward, passing NULL
1113          * for match_start so lines_match will try to match the entire
1114          * line */
1115         return lines_match (&next, lines, visible_only,
1116                             slice, NULL, match_end);
1117 }
1118
1119 gboolean
1120 empathy_text_iter_backward_search (const GtkTextIter   *iter,
1121                                   const gchar         *str,
1122                                   GtkTextIter         *match_start,
1123                                   GtkTextIter         *match_end,
1124                                   const GtkTextIter   *limit)
1125 {
1126         gchar **lines = NULL;
1127         GtkTextIter match;
1128         gboolean retval = FALSE;
1129         GtkTextIter search;
1130         gboolean visible_only;
1131         gboolean slice;
1132
1133         g_return_val_if_fail (iter != NULL, FALSE);
1134         g_return_val_if_fail (str != NULL, FALSE);
1135
1136         if (limit && gtk_text_iter_compare (iter, limit) <= 0)
1137                 return FALSE;
1138
1139         if (*str == '\0')
1140         {
1141                 /* If we can move one char, return the empty string there */
1142                 match = *iter;
1143
1144                 if (gtk_text_iter_backward_char (&match))
1145                 {
1146                         if (limit && gtk_text_iter_equal (&match, limit))
1147                                 return FALSE;
1148
1149                         if (match_start)
1150                                 *match_start = match;
1151                         if (match_end)
1152                                 *match_end = match;
1153                         return TRUE;
1154                 }
1155                 else
1156                 {
1157                         return FALSE;
1158                 }
1159         }
1160
1161         visible_only = TRUE;
1162         slice = TRUE;
1163
1164         /* locate all lines */
1165         lines = strbreakup (str, "\n", -1);
1166
1167         search = *iter;
1168
1169         while (TRUE)
1170         {
1171                 /* This loop has an inefficient worst-case, where
1172                  * gtk_text_iter_get_text () is called repeatedly on
1173                  * a single line.
1174                  */
1175                 GtkTextIter end;
1176
1177                 if (limit && gtk_text_iter_compare (&search, limit) <= 0)
1178                         break;
1179
1180                 if (backward_lines_match (&search, (const gchar**)lines,
1181                                           visible_only, slice, &match, &end))
1182                 {
1183                         if (limit == NULL || (limit &&
1184                                               gtk_text_iter_compare (&end, limit) > 0))
1185                         {
1186                                 retval = TRUE;
1187
1188                                 if (match_start)
1189                                         *match_start = match;
1190                                 if (match_end)
1191                                         *match_end = end;
1192                         }
1193                         break;
1194                 }
1195
1196                 if (gtk_text_iter_get_line_offset (&search) == 0)
1197                 {
1198                         if (!gtk_text_iter_backward_line (&search))
1199                                 break;
1200                 }
1201                 else
1202                 {
1203                         gtk_text_iter_set_line_offset (&search, 0);
1204                 }
1205         }
1206
1207         g_strfreev ((gchar**)lines);
1208
1209         return retval;
1210 }
1211
1212 gboolean
1213 empathy_window_get_is_visible (GtkWindow *window)
1214 {
1215         GdkWindowState  state;
1216         GdkWindow      *gdk_window;
1217
1218         g_return_val_if_fail (GTK_IS_WINDOW (window), FALSE);
1219
1220         gdk_window = GTK_WIDGET (window)->window;
1221         if (!gdk_window) {
1222                 return FALSE;
1223         }
1224
1225         state = gdk_window_get_state (gdk_window);
1226         if (state & (GDK_WINDOW_STATE_WITHDRAWN | GDK_WINDOW_STATE_ICONIFIED)) {
1227                 return FALSE;
1228         }
1229
1230         return TRUE;
1231 }
1232
1233 void 
1234 empathy_window_iconify (GtkWindow *window, GtkStatusIcon *status_icon)
1235 {
1236         GdkRectangle  icon_location;
1237         gulong        data[4];
1238         Display      *dpy;
1239         GdkWindow    *gdk_window;
1240
1241         gtk_status_icon_get_geometry (status_icon, NULL, &icon_location, NULL);
1242         gdk_window = GTK_WIDGET (window)->window;
1243         dpy = gdk_x11_drawable_get_xdisplay (gdk_window);
1244
1245         data[0] = icon_location.x;
1246         data[1] = icon_location.y;
1247         data[2] = icon_location.width;
1248         data[3] = icon_location.height;
1249
1250         XChangeProperty (dpy,
1251                          GDK_WINDOW_XID (gdk_window),
1252                          gdk_x11_get_xatom_by_name_for_display (gdk_drawable_get_display (gdk_window),
1253                          "_NET_WM_ICON_GEOMETRY"),
1254                          XA_CARDINAL, 32, PropModeReplace,
1255                          (guchar *)&data, 4);
1256
1257         gtk_window_set_skip_taskbar_hint (window, TRUE);
1258         gtk_window_iconify (window);
1259 }
1260
1261 /* Takes care of moving the window to the current workspace. */
1262 void
1263 empathy_window_present (GtkWindow *window,
1264                         gboolean   steal_focus)
1265 {
1266         guint32 timestamp;
1267
1268         g_return_if_fail (GTK_IS_WINDOW (window));
1269
1270         /* There are three cases: hidden, visible, visible on another
1271          * workspace.
1272          */
1273
1274         if (!empathy_window_get_is_visible (window)) {
1275                 /* Hide it so present brings it to the current workspace. */
1276                 gtk_widget_hide (GTK_WIDGET (window));
1277         }
1278
1279         timestamp = gtk_get_current_event_time ();
1280         gtk_window_set_skip_taskbar_hint (window, FALSE);
1281         gtk_window_present_with_time (window, timestamp);
1282         /* FIXME: This shouldn't be required as gtk_window_present's doc says
1283          *        it deiconify automatically. */
1284         gtk_window_deiconify (window);
1285 }
1286
1287 GtkWindow *
1288 empathy_get_toplevel_window (GtkWidget *widget)
1289 {
1290         GtkWidget *toplevel;
1291
1292         g_return_val_if_fail (GTK_IS_WIDGET (widget), NULL);
1293
1294         toplevel = gtk_widget_get_toplevel (widget);
1295         if (GTK_IS_WINDOW (toplevel) &&
1296             GTK_WIDGET_TOPLEVEL (toplevel)) {
1297                 return GTK_WINDOW (toplevel);
1298         }
1299
1300         return NULL;
1301 }
1302
1303 /* The URL opening code can't handle schemeless strings, so we try to be
1304  * smart and add http if there is no scheme or doesn't look like a mail
1305  * address. This should work in most cases, and let us click on strings
1306  * like "www.gnome.org".
1307  */
1308 static gchar *
1309 fixup_url (const gchar *url)
1310 {
1311         if (g_str_has_prefix (url, "ghelp:") ||
1312             g_str_has_prefix (url, "mailto:") ||
1313             strstr (url, ":/")) {
1314                 return NULL;
1315         }
1316
1317         if (strstr (url, "@")) {
1318                 return g_strdup_printf ("mailto:%s", url);
1319         }
1320
1321         return g_strdup_printf ("http://%s", url);
1322 }
1323
1324 void
1325 empathy_url_show (const char *url)
1326 {
1327         gchar  *real_url;
1328         GError *error = NULL;
1329
1330         real_url = fixup_url (url);
1331         if (real_url) {
1332                 url = real_url;
1333         }
1334
1335         /* FIXME: this does not work for multihead, we should use
1336          * GdkAppLaunchContext or gtk_show_url, see bug #514396.
1337          */
1338         g_app_info_launch_default_for_uri (url, NULL, &error);
1339         if (error) {
1340                 GtkWidget *dialog;
1341
1342                 dialog = gtk_message_dialog_new (NULL, 0,
1343                                                  GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, 
1344                                                  _("Unable to open URI"));
1345                 gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
1346                                                           "%s", error->message);
1347
1348                 g_signal_connect (dialog, "response",
1349                                   G_CALLBACK (gtk_widget_destroy),
1350                                   NULL);
1351                 gtk_window_present (GTK_WINDOW (dialog));
1352
1353                 g_clear_error (&error);
1354         }
1355
1356         g_free (real_url);
1357 }
1358
1359 static void
1360 link_button_hook (GtkLinkButton *button,
1361                   const gchar *link,
1362                   gpointer user_data)
1363 {
1364         empathy_url_show (link);
1365 }
1366
1367 GtkWidget *
1368 empathy_link_button_new (const gchar *url,
1369                         const gchar *title)
1370 {
1371         static gboolean hook = FALSE;
1372
1373         if (!hook) {
1374                 hook = TRUE;
1375                 gtk_link_button_set_uri_hook (link_button_hook, NULL, NULL);
1376         }
1377
1378         return gtk_link_button_new_with_label (url, title);
1379 }
1380
1381 void
1382 empathy_toggle_button_set_state_quietly (GtkWidget *widget,
1383                                         GCallback  callback,
1384                                         gpointer   user_data,
1385                                         gboolean   active)
1386 {
1387         g_return_if_fail (GTK_IS_TOGGLE_BUTTON (widget));
1388
1389         g_signal_handlers_block_by_func (widget, callback, user_data);
1390         g_object_set (widget, "active", active, NULL);
1391         g_signal_handlers_unblock_by_func (widget, callback, user_data);
1392 }
1393
1394 GtkTextTag *
1395 empathy_text_buffer_tag_set (GtkTextBuffer *buffer,
1396                              const gchar   *tag_name,
1397                              const gchar   *first_property_name,
1398                              ...)
1399 {
1400         GtkTextTagTable *table;
1401         GtkTextTag      *tag;
1402
1403         g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
1404         g_return_val_if_fail (tag_name != NULL, NULL);
1405
1406         table = gtk_text_buffer_get_tag_table (buffer);
1407         tag = gtk_text_tag_table_lookup (table, tag_name);
1408
1409         if (!tag) {
1410                 tag = gtk_text_tag_new (tag_name);
1411                 gtk_text_tag_table_add (table, tag);
1412                 g_object_unref (tag);
1413         } else {
1414                 /* Clear the old values so that we don't affect the new theme. */
1415                 g_object_set (tag,
1416                               "background-set", FALSE,
1417                               "foreground-set", FALSE,
1418                               "invisible-set", FALSE,
1419                               "justification-set", FALSE,
1420                               "paragraph-background-set", FALSE,
1421                               "pixels-above-lines-set", FALSE,
1422                               "pixels-below-lines-set", FALSE,
1423                               "rise-set", FALSE,
1424                               "scale-set", FALSE,
1425                               "size-set", FALSE,
1426                               "style-set", FALSE,
1427                               "weight-set", FALSE,
1428                               NULL);
1429         }
1430
1431         if (first_property_name) {
1432                 va_list list;
1433
1434                 va_start (list, first_property_name);
1435                 g_object_set_valist (G_OBJECT (tag), first_property_name, list);
1436                 va_end (list);
1437         }
1438
1439         return tag;
1440 }
1441