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