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