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