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