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