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