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