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