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