]> git.0d.be Git - empathy.git/blob - libempathy-gtk/gossip-ui-utils.c
[darcs-to-svn @ Fix setting presence]
[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 (McPresence state)
357 {
358         const gchar *stock;
359
360         stock = gossip_stock_for_state (state);
361
362         return gossip_stock_render (stock, GTK_ICON_SIZE_MENU);
363 }
364
365 GdkPixbuf *
366 gossip_pixbuf_for_presence (GossipPresence *presence)
367 {
368         McPresence state;
369
370         g_return_val_if_fail (GOSSIP_IS_PRESENCE (presence),
371                               gossip_pixbuf_offline ());
372
373         state = gossip_presence_get_state (presence);
374
375         return gossip_pixbuf_for_presence_state (state);
376 }
377
378 GdkPixbuf *
379 gossip_pixbuf_for_contact (GossipContact *contact)
380 {
381         GossipPresence     *presence;
382         GossipSubscription  subscription;
383
384         g_return_val_if_fail (GOSSIP_IS_CONTACT (contact),
385                               gossip_pixbuf_offline ());
386
387         presence = gossip_contact_get_presence (contact);
388
389         if (presence) {
390                 return gossip_pixbuf_for_presence (presence);
391         }
392
393         subscription = gossip_contact_get_subscription (contact);
394
395         if (subscription != GOSSIP_SUBSCRIPTION_BOTH &&
396             subscription != GOSSIP_SUBSCRIPTION_TO) {
397                 return gossip_stock_render (GOSSIP_STOCK_PENDING,
398                                             GTK_ICON_SIZE_MENU);
399         }
400
401         return gossip_pixbuf_offline ();
402 }
403
404 GdkPixbuf *
405 gossip_pixbuf_offline (void)
406 {
407         return gossip_stock_render (GOSSIP_STOCK_OFFLINE,
408                                     GTK_ICON_SIZE_MENU);
409 }
410
411 GdkPixbuf *
412 gossip_pixbuf_avatar_from_contact (GossipContact *contact)
413 {
414         GdkPixbuf       *pixbuf;
415         GdkPixbufLoader *loader;
416         GossipAvatar    *avatar;
417         GError          *error = NULL;
418
419         g_return_val_if_fail (GOSSIP_IS_CONTACT (contact), NULL);
420
421         avatar = gossip_contact_get_avatar (contact);
422         if (!avatar) {
423                 return NULL;
424         }
425
426         loader = gdk_pixbuf_loader_new ();
427
428         if (!gdk_pixbuf_loader_write (loader, avatar->data, avatar->len, &error)) {
429                 g_warning ("Couldn't write avatar image:%p with "
430                            "length:%" G_GSIZE_FORMAT " to pixbuf loader: %s",
431                            avatar->data, avatar->len, error->message);
432                 g_error_free (error);
433                 return NULL;
434         }
435
436         gdk_pixbuf_loader_close (loader, NULL);
437
438         pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
439
440         g_object_ref (pixbuf);
441         g_object_unref (loader);
442
443         return pixbuf;
444 }
445
446 static void
447 pixbuf_from_avatar_size_prepared_cb (GdkPixbufLoader *loader,
448                                      int              width,
449                                      int              height,
450                                      struct SizeData *data)
451 {
452         g_return_if_fail (width > 0 && height > 0);
453
454         if (data->preserve_aspect_ratio && (data->width > 0 || data->height > 0)) {
455                 if (width < data->width && height < data->height) {
456                         width = width;
457                         height = height;
458                 }
459
460                 if (data->width < 0) {
461                         width = width * (double) data->height / (gdouble) height;
462                         height = data->height;
463                 } else if (data->height < 0) {
464                         height = height * (double) data->width / (double) width;
465                         width = data->width;
466                 } else if ((double) height * (double) data->width >
467                            (double) width * (double) data->height) {
468                         width = 0.5 + (double) width * (double) data->height / (double) height;
469                         height = data->height;
470                 } else {
471                         height = 0.5 + (double) height * (double) data->width / (double) width;
472                         width = data->width;
473                 }
474         } else {
475                 if (data->width > 0) {
476                         width = data->width;
477                 }
478
479                 if (data->height > 0) {
480                         height = data->height;
481                 }
482         }
483
484         gdk_pixbuf_loader_set_size (loader, width, height);
485 }
486
487 GdkPixbuf *
488 gossip_pixbuf_from_avatar_scaled (GossipAvatar *avatar,
489                                   gint          width,
490                                   gint          height)
491 {
492         GdkPixbuf        *pixbuf;
493         GdkPixbufLoader  *loader;
494         struct SizeData   data;
495         GError           *error = NULL;
496
497         if (!avatar) {
498                 return NULL;
499         }
500
501         data.width = width;
502         data.height = height;
503         data.preserve_aspect_ratio = TRUE;
504
505         loader = gdk_pixbuf_loader_new ();
506
507         g_signal_connect (loader, "size-prepared",
508                           G_CALLBACK (pixbuf_from_avatar_size_prepared_cb),
509                           &data);
510
511         if (!gdk_pixbuf_loader_write (loader, avatar->data, avatar->len, &error)) {
512                 g_warning ("Couldn't write avatar image:%p with "
513                            "length:%" G_GSIZE_FORMAT " to pixbuf loader: %s",
514                            avatar->data, avatar->len, error->message);
515                 g_error_free (error);
516                 return NULL;
517         }
518
519         gdk_pixbuf_loader_close (loader, NULL);
520
521         pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
522
523         g_object_ref (pixbuf);
524         g_object_unref (loader);
525
526         return pixbuf;
527 }
528
529 GdkPixbuf *
530 gossip_pixbuf_avatar_from_contact_scaled (GossipContact *contact,
531                                           gint           width,
532                                           gint           height)
533 {
534         GossipAvatar *avatar;
535
536         g_return_val_if_fail (GOSSIP_IS_CONTACT (contact), NULL);
537
538         avatar = gossip_contact_get_avatar (contact);
539
540         return gossip_pixbuf_from_avatar_scaled (avatar, width, height);
541 }
542 /* Stolen from GtkSourceView, hence the weird intendation. Please keep it like
543  * that to make it easier to apply changes from the original code.
544  */
545 #define GTK_TEXT_UNKNOWN_CHAR 0xFFFC
546
547 /* this function acts like g_utf8_offset_to_pointer() except that if it finds a
548  * decomposable character it consumes the decomposition length from the given
549  * offset.  So it's useful when the offset was calculated for the normalized
550  * version of str, but we need a pointer to str itself. */
551 static const gchar *
552 pointer_from_offset_skipping_decomp (const gchar *str, gint offset)
553 {
554         gchar *casefold, *normal;
555         const gchar *p, *q;
556
557         p = str;
558         while (offset > 0)
559         {
560                 q = g_utf8_next_char (p);
561                 casefold = g_utf8_casefold (p, q - p);
562                 normal = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
563                 offset -= g_utf8_strlen (normal, -1);
564                 g_free (casefold);
565                 g_free (normal);
566                 p = q;
567         }
568         return p;
569 }
570
571 static const gchar *
572 g_utf8_strcasestr (const gchar *haystack, const gchar *needle)
573 {
574         gsize needle_len;
575         gsize haystack_len;
576         const gchar *ret = NULL;
577         gchar *p;
578         gchar *casefold;
579         gchar *caseless_haystack;
580         gint i;
581
582         g_return_val_if_fail (haystack != NULL, NULL);
583         g_return_val_if_fail (needle != NULL, NULL);
584
585         casefold = g_utf8_casefold (haystack, -1);
586         caseless_haystack = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
587         g_free (casefold);
588
589         needle_len = g_utf8_strlen (needle, -1);
590         haystack_len = g_utf8_strlen (caseless_haystack, -1);
591
592         if (needle_len == 0)
593         {
594                 ret = (gchar *)haystack;
595                 goto finally_1;
596         }
597
598         if (haystack_len < needle_len)
599         {
600                 ret = NULL;
601                 goto finally_1;
602         }
603
604         p = (gchar*)caseless_haystack;
605         needle_len = strlen (needle);
606         i = 0;
607
608         while (*p)
609         {
610                 if ((strncmp (p, needle, needle_len) == 0))
611                 {
612                         ret = pointer_from_offset_skipping_decomp (haystack, i);
613                         goto finally_1;
614                 }
615
616                 p = g_utf8_next_char (p);
617                 i++;
618         }
619
620 finally_1:
621         g_free (caseless_haystack);
622
623         return ret;
624 }
625
626 static gboolean
627 g_utf8_caselessnmatch (const char *s1, const char *s2,
628                        gssize n1, gssize n2)
629 {
630         gchar *casefold;
631         gchar *normalized_s1;
632         gchar *normalized_s2;
633         gint len_s1;
634         gint len_s2;
635         gboolean ret = FALSE;
636
637         g_return_val_if_fail (s1 != NULL, FALSE);
638         g_return_val_if_fail (s2 != NULL, FALSE);
639         g_return_val_if_fail (n1 > 0, FALSE);
640         g_return_val_if_fail (n2 > 0, FALSE);
641
642         casefold = g_utf8_casefold (s1, n1);
643         normalized_s1 = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
644         g_free (casefold);
645
646         casefold = g_utf8_casefold (s2, n2);
647         normalized_s2 = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
648         g_free (casefold);
649
650         len_s1 = strlen (normalized_s1);
651         len_s2 = strlen (normalized_s2);
652
653         if (len_s1 < len_s2)
654                 goto finally_2;
655
656         ret = (strncmp (normalized_s1, normalized_s2, len_s2) == 0);
657
658 finally_2:
659         g_free (normalized_s1);
660         g_free (normalized_s2);
661
662         return ret;
663 }
664
665 static void
666 forward_chars_with_skipping (GtkTextIter *iter,
667                              gint         count,
668                              gboolean     skip_invisible,
669                              gboolean     skip_nontext,
670                              gboolean     skip_decomp)
671 {
672         gint i;
673
674         g_return_if_fail (count >= 0);
675
676         i = count;
677
678         while (i > 0)
679         {
680                 gboolean ignored = FALSE;
681
682                 /* minimal workaround to avoid the infinite loop of bug #168247.
683                  * It doesn't fix the problemjust the symptom...
684                  */
685                 if (gtk_text_iter_is_end (iter))
686                         return;
687
688                 if (skip_nontext && gtk_text_iter_get_char (iter) == GTK_TEXT_UNKNOWN_CHAR)
689                         ignored = TRUE;
690
691                 if (!ignored && skip_invisible &&
692                     /* _gtk_text_btree_char_is_invisible (iter)*/ FALSE)
693                         ignored = TRUE;
694
695                 if (!ignored && skip_decomp)
696                 {
697                         /* being UTF8 correct sucks; this accounts for extra
698                            offsets coming from canonical decompositions of
699                            UTF8 characters (e.g. accented characters) which
700                            g_utf8_normalize() performs */
701                         gchar *normal;
702                         gchar buffer[6];
703                         gint buffer_len;
704
705                         buffer_len = g_unichar_to_utf8 (gtk_text_iter_get_char (iter), buffer);
706                         normal = g_utf8_normalize (buffer, buffer_len, G_NORMALIZE_NFD);
707                         i -= (g_utf8_strlen (normal, -1) - 1);
708                         g_free (normal);
709                 }
710
711                 gtk_text_iter_forward_char (iter);
712
713                 if (!ignored)
714                         --i;
715         }
716 }
717
718 static gboolean
719 lines_match (const GtkTextIter *start,
720              const gchar      **lines,
721              gboolean           visible_only,
722              gboolean           slice,
723              GtkTextIter       *match_start,
724              GtkTextIter       *match_end)
725 {
726         GtkTextIter next;
727         gchar *line_text;
728         const gchar *found;
729         gint offset;
730
731         if (*lines == NULL || **lines == '\0')
732         {
733                 if (match_start)
734                         *match_start = *start;
735                 if (match_end)
736                         *match_end = *start;
737                 return TRUE;
738         }
739
740         next = *start;
741         gtk_text_iter_forward_line (&next);
742
743         /* No more text in buffer, but *lines is nonempty */
744         if (gtk_text_iter_equal (start, &next))
745                 return FALSE;
746
747         if (slice)
748         {
749                 if (visible_only)
750                         line_text = gtk_text_iter_get_visible_slice (start, &next);
751                 else
752                         line_text = gtk_text_iter_get_slice (start, &next);
753         }
754         else
755         {
756                 if (visible_only)
757                         line_text = gtk_text_iter_get_visible_text (start, &next);
758                 else
759                         line_text = gtk_text_iter_get_text (start, &next);
760         }
761
762         if (match_start) /* if this is the first line we're matching */
763         {
764                 found = g_utf8_strcasestr (line_text, *lines);
765         }
766         else
767         {
768                 /* If it's not the first line, we have to match from the
769                  * start of the line.
770                  */
771                 if (g_utf8_caselessnmatch (line_text, *lines, strlen (line_text),
772                                            strlen (*lines)))
773                         found = line_text;
774                 else
775                         found = NULL;
776         }
777
778         if (found == NULL)
779         {
780                 g_free (line_text);
781                 return FALSE;
782         }
783
784         /* Get offset to start of search string */
785         offset = g_utf8_strlen (line_text, found - line_text);
786
787         next = *start;
788
789         /* If match start needs to be returned, set it to the
790          * start of the search string.
791          */
792         forward_chars_with_skipping (&next, offset, visible_only, !slice, FALSE);
793         if (match_start)
794         {
795                 *match_start = next;
796         }
797
798         /* Go to end of search string */
799         forward_chars_with_skipping (&next, g_utf8_strlen (*lines, -1), visible_only, !slice, TRUE);
800
801         g_free (line_text);
802
803         ++lines;
804
805         if (match_end)
806                 *match_end = next;
807
808         /* pass NULL for match_start, since we don't need to find the
809          * start again.
810          */
811         return lines_match (&next, lines, visible_only, slice, NULL, match_end);
812 }
813
814 /* strsplit () that retains the delimiter as part of the string. */
815 static gchar **
816 strbreakup (const char *string,
817             const char *delimiter,
818             gint        max_tokens)
819 {
820         GSList *string_list = NULL, *slist;
821         gchar **str_array, *s, *casefold, *new_string;
822         guint i, n = 1;
823
824         g_return_val_if_fail (string != NULL, NULL);
825         g_return_val_if_fail (delimiter != NULL, NULL);
826
827         if (max_tokens < 1)
828                 max_tokens = G_MAXINT;
829
830         s = strstr (string, delimiter);
831         if (s)
832         {
833                 guint delimiter_len = strlen (delimiter);
834
835                 do
836                 {
837                         guint len;
838
839                         len = s - string + delimiter_len;
840                         new_string = g_new (gchar, len + 1);
841                         strncpy (new_string, string, len);
842                         new_string[len] = 0;
843                         casefold = g_utf8_casefold (new_string, -1);
844                         g_free (new_string);
845                         new_string = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
846                         g_free (casefold);
847                         string_list = g_slist_prepend (string_list, new_string);
848                         n++;
849                         string = s + delimiter_len;
850                         s = strstr (string, delimiter);
851                 } while (--max_tokens && s);
852         }
853
854         if (*string)
855         {
856                 n++;
857                 casefold = g_utf8_casefold (string, -1);
858                 new_string = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
859                 g_free (casefold);
860                 string_list = g_slist_prepend (string_list, new_string);
861         }
862
863         str_array = g_new (gchar*, n);
864
865         i = n - 1;
866
867         str_array[i--] = NULL;
868         for (slist = string_list; slist; slist = slist->next)
869                 str_array[i--] = slist->data;
870
871         g_slist_free (string_list);
872
873         return str_array;
874 }
875
876 gboolean
877 gossip_text_iter_forward_search (const GtkTextIter   *iter,
878                                  const gchar         *str,
879                                  GtkTextIter         *match_start,
880                                  GtkTextIter         *match_end,
881                                  const GtkTextIter   *limit)
882 {
883         gchar **lines = NULL;
884         GtkTextIter match;
885         gboolean retval = FALSE;
886         GtkTextIter search;
887         gboolean visible_only;
888         gboolean slice;
889
890         g_return_val_if_fail (iter != NULL, FALSE);
891         g_return_val_if_fail (str != NULL, FALSE);
892
893         if (limit && gtk_text_iter_compare (iter, limit) >= 0)
894                 return FALSE;
895
896         if (*str == '\0') {
897                 /* If we can move one char, return the empty string there */
898                 match = *iter;
899
900                 if (gtk_text_iter_forward_char (&match)) {
901                         if (limit && gtk_text_iter_equal (&match, limit)) {
902                                 return FALSE;
903                         }
904
905                         if (match_start) {
906                                 *match_start = match;
907                         }
908                         if (match_end) {
909                                 *match_end = match;
910                         }
911                         return TRUE;
912                 } else {
913                         return FALSE;
914                 }
915         }
916
917         visible_only = TRUE;
918         slice = FALSE;
919
920         /* locate all lines */
921         lines = strbreakup (str, "\n", -1);
922
923         search = *iter;
924
925         do {
926                 /* This loop has an inefficient worst-case, where
927                  * gtk_text_iter_get_text () is called repeatedly on
928                  * a single line.
929                  */
930                 GtkTextIter end;
931
932                 if (limit && gtk_text_iter_compare (&search, limit) >= 0) {
933                         break;
934                 }
935
936                 if (lines_match (&search, (const gchar**)lines,
937                                  visible_only, slice, &match, &end)) {
938                         if (limit == NULL ||
939                             (limit && gtk_text_iter_compare (&end, limit) <= 0)) {
940                                 retval = TRUE;
941
942                                 if (match_start) {
943                                         *match_start = match;
944                                 }
945                                 if (match_end) {
946                                         *match_end = end;
947                                 }
948                         }
949                         break;
950                 }
951         } while (gtk_text_iter_forward_line (&search));
952
953         g_strfreev ((gchar**)lines);
954
955         return retval;
956 }
957
958 static const gchar *
959 g_utf8_strrcasestr (const gchar *haystack, const gchar *needle)
960 {
961         gsize needle_len;
962         gsize haystack_len;
963         const gchar *ret = NULL;
964         gchar *p;
965         gchar *casefold;
966         gchar *caseless_haystack;
967         gint i;
968
969         g_return_val_if_fail (haystack != NULL, NULL);
970         g_return_val_if_fail (needle != NULL, NULL);
971
972         casefold = g_utf8_casefold (haystack, -1);
973         caseless_haystack = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
974         g_free (casefold);
975
976         needle_len = g_utf8_strlen (needle, -1);
977         haystack_len = g_utf8_strlen (caseless_haystack, -1);
978
979         if (needle_len == 0)
980         {
981                 ret = (gchar *)haystack;
982                 goto finally_1;
983         }
984
985         if (haystack_len < needle_len)
986         {
987                 ret = NULL;
988                 goto finally_1;
989         }
990
991         i = haystack_len - needle_len;
992         p = g_utf8_offset_to_pointer (caseless_haystack, i);
993         needle_len = strlen (needle);
994
995         while (p >= caseless_haystack)
996         {
997                 if (strncmp (p, needle, needle_len) == 0)
998                 {
999                         ret = pointer_from_offset_skipping_decomp (haystack, i);
1000                         goto finally_1;
1001                 }
1002
1003                 p = g_utf8_prev_char (p);
1004                 i--;
1005         }
1006
1007 finally_1:
1008         g_free (caseless_haystack);
1009
1010         return ret;
1011 }
1012
1013 static gboolean
1014 backward_lines_match (const GtkTextIter *start,
1015                       const gchar      **lines,
1016                       gboolean           visible_only,
1017                       gboolean           slice,
1018                       GtkTextIter       *match_start,
1019                       GtkTextIter       *match_end)
1020 {
1021         GtkTextIter line, next;
1022         gchar *line_text;
1023         const gchar *found;
1024         gint offset;
1025
1026         if (*lines == NULL || **lines == '\0')
1027         {
1028                 if (match_start)
1029                         *match_start = *start;
1030                 if (match_end)
1031                         *match_end = *start;
1032                 return TRUE;
1033         }
1034
1035         line = next = *start;
1036         if (gtk_text_iter_get_line_offset (&next) == 0)
1037         {
1038                 if (!gtk_text_iter_backward_line (&next))
1039                         return FALSE;
1040         }
1041         else
1042                 gtk_text_iter_set_line_offset (&next, 0);
1043
1044         if (slice)
1045         {
1046                 if (visible_only)
1047                         line_text = gtk_text_iter_get_visible_slice (&next, &line);
1048                 else
1049                         line_text = gtk_text_iter_get_slice (&next, &line);
1050         }
1051         else
1052         {
1053                 if (visible_only)
1054                         line_text = gtk_text_iter_get_visible_text (&next, &line);
1055                 else
1056                         line_text = gtk_text_iter_get_text (&next, &line);
1057         }
1058
1059         if (match_start) /* if this is the first line we're matching */
1060         {
1061                 found = g_utf8_strrcasestr (line_text, *lines);
1062         }
1063         else
1064         {
1065                 /* If it's not the first line, we have to match from the
1066                  * start of the line.
1067                  */
1068                 if (g_utf8_caselessnmatch (line_text, *lines, strlen (line_text),
1069                                            strlen (*lines)))
1070                         found = line_text;
1071                 else
1072                         found = NULL;
1073         }
1074
1075         if (found == NULL)
1076         {
1077                 g_free (line_text);
1078                 return FALSE;
1079         }
1080
1081         /* Get offset to start of search string */
1082         offset = g_utf8_strlen (line_text, found - line_text);
1083
1084         forward_chars_with_skipping (&next, offset, visible_only, !slice, FALSE);
1085
1086         /* If match start needs to be returned, set it to the
1087          * start of the search string.
1088          */
1089         if (match_start)
1090         {
1091                 *match_start = next;
1092         }
1093
1094         /* Go to end of search string */
1095         forward_chars_with_skipping (&next, g_utf8_strlen (*lines, -1), visible_only, !slice, TRUE);
1096
1097         g_free (line_text);
1098
1099         ++lines;
1100
1101         if (match_end)
1102                 *match_end = next;
1103
1104         /* try to match the rest of the lines forward, passing NULL
1105          * for match_start so lines_match will try to match the entire
1106          * line */
1107         return lines_match (&next, lines, visible_only,
1108                             slice, NULL, match_end);
1109 }
1110
1111 gboolean
1112 gossip_text_iter_backward_search (const GtkTextIter   *iter,
1113                                   const gchar         *str,
1114                                   GtkTextIter         *match_start,
1115                                   GtkTextIter         *match_end,
1116                                   const GtkTextIter   *limit)
1117 {
1118         gchar **lines = NULL;
1119         GtkTextIter match;
1120         gboolean retval = FALSE;
1121         GtkTextIter search;
1122         gboolean visible_only;
1123         gboolean slice;
1124
1125         g_return_val_if_fail (iter != NULL, FALSE);
1126         g_return_val_if_fail (str != NULL, FALSE);
1127
1128         if (limit && gtk_text_iter_compare (iter, limit) <= 0)
1129                 return FALSE;
1130
1131         if (*str == '\0')
1132         {
1133                 /* If we can move one char, return the empty string there */
1134                 match = *iter;
1135
1136                 if (gtk_text_iter_backward_char (&match))
1137                 {
1138                         if (limit && gtk_text_iter_equal (&match, limit))
1139                                 return FALSE;
1140
1141                         if (match_start)
1142                                 *match_start = match;
1143                         if (match_end)
1144                                 *match_end = match;
1145                         return TRUE;
1146                 }
1147                 else
1148                 {
1149                         return FALSE;
1150                 }
1151         }
1152
1153         visible_only = TRUE;
1154         slice = TRUE;
1155
1156         /* locate all lines */
1157         lines = strbreakup (str, "\n", -1);
1158
1159         search = *iter;
1160
1161         while (TRUE)
1162         {
1163                 /* This loop has an inefficient worst-case, where
1164                  * gtk_text_iter_get_text () is called repeatedly on
1165                  * a single line.
1166                  */
1167                 GtkTextIter end;
1168
1169                 if (limit && gtk_text_iter_compare (&search, limit) <= 0)
1170                         break;
1171
1172                 if (backward_lines_match (&search, (const gchar**)lines,
1173                                           visible_only, slice, &match, &end))
1174                 {
1175                         if (limit == NULL || (limit &&
1176                                               gtk_text_iter_compare (&end, limit) > 0))
1177                         {
1178                                 retval = TRUE;
1179
1180                                 if (match_start)
1181                                         *match_start = match;
1182                                 if (match_end)
1183                                         *match_end = end;
1184                         }
1185                         break;
1186                 }
1187
1188                 if (gtk_text_iter_get_line_offset (&search) == 0)
1189                 {
1190                         if (!gtk_text_iter_backward_line (&search))
1191                                 break;
1192                 }
1193                 else
1194                 {
1195                         gtk_text_iter_set_line_offset (&search, 0);
1196                 }
1197         }
1198
1199         g_strfreev ((gchar**)lines);
1200
1201         return retval;
1202 }
1203
1204 static gboolean
1205 window_get_is_on_current_workspace (GtkWindow *window)
1206 {
1207         GdkWindow *gdk_window;
1208
1209         gdk_window = GTK_WIDGET (window)->window;
1210         if (gdk_window) {
1211                 return !(gdk_window_get_state (gdk_window) &
1212                          GDK_WINDOW_STATE_ICONIFIED);
1213         } else {
1214                 return FALSE;
1215         }
1216 }
1217
1218 /* Checks if the window is visible as in visible on the current workspace. */
1219 gboolean
1220 gossip_window_get_is_visible (GtkWindow *window)
1221 {
1222         gboolean visible;
1223
1224         g_return_val_if_fail (window != NULL, FALSE);
1225
1226         g_object_get (window,
1227                       "visible", &visible,
1228                       NULL);
1229
1230         return visible && window_get_is_on_current_workspace (window);
1231 }
1232
1233 /* Takes care of moving the window to the current workspace. */
1234 void
1235 gossip_window_present (GtkWindow *window,
1236                        gboolean   steal_focus)
1237 {
1238         gboolean visible;
1239         gboolean on_current;
1240         guint32  timestamp;
1241
1242         g_return_if_fail (window != NULL);
1243
1244         /* There are three cases: hidden, visible, visible on another
1245          * workspace.
1246          */
1247
1248         g_object_get (window,
1249                       "visible", &visible,
1250                       NULL);
1251
1252         on_current = window_get_is_on_current_workspace (window);
1253
1254         if (visible && !on_current) {
1255                 /* Hide it so present brings it to the current workspace. */
1256                 gtk_widget_hide (GTK_WIDGET (window));
1257         }
1258
1259         timestamp = gtk_get_current_event_time ();
1260         if (steal_focus && timestamp != GDK_CURRENT_TIME) {
1261                 gtk_window_present_with_time (window, timestamp);
1262         } else {
1263                 gtk_window_present (window);
1264         }
1265 }
1266
1267 /* The URL opening code can't handle schemeless strings, so we try to be
1268  * smart and add http if there is no scheme or doesn't look like a mail
1269  * address. This should work in most cases, and let us click on strings
1270  * like "www.gnome.org".
1271  */
1272 static gchar *
1273 fixup_url (const gchar *url)
1274 {
1275         gchar *real_url;
1276
1277         if (!g_str_has_prefix (url, "http://") &&
1278             !strstr (url, ":/") &&
1279             !strstr (url, "@")) {
1280                 real_url = g_strdup_printf ("http://%s", url);
1281         } else {
1282                 real_url = g_strdup (url);
1283         }
1284
1285         return real_url;
1286 }
1287
1288 void
1289 gossip_url_show (const char *url)
1290 {
1291         gchar  *real_url;
1292         GError *error = NULL;
1293
1294         real_url = fixup_url (url);
1295         gnome_url_show (real_url, &error);
1296         if (error) {
1297                 g_warning ("Couldn't show URL:'%s'", real_url);
1298                 g_error_free (error);
1299         }
1300
1301         g_free (real_url);
1302 }
1303
1304 static void
1305 link_button_hook (GtkLinkButton *button,
1306                   const gchar *link,
1307                   gpointer user_data)
1308 {
1309         gossip_url_show (link);
1310 }
1311
1312 GtkWidget *
1313 gossip_link_button_new (const gchar *url,
1314                         const gchar *title)
1315 {
1316         static gboolean hook = FALSE;
1317
1318         if (!hook) {
1319                 hook = TRUE;
1320                 gtk_link_button_set_uri_hook (link_button_hook, NULL, NULL);
1321         }
1322
1323         return gtk_link_button_new_with_label (url, title);
1324 }
1325
1326 /* FIXME: Do this in a proper way at some point, probably in GTK+? */
1327 void
1328 gossip_window_set_default_icon_name (const gchar *name)
1329 {
1330         gtk_window_set_default_icon_name (name);
1331 }
1332
1333 void
1334 gossip_toggle_button_set_state_quietly (GtkWidget *widget,
1335                                         GCallback  callback,
1336                                         gpointer   user_data,
1337                                         gboolean   active)
1338 {
1339         g_return_if_fail (GTK_IS_TOGGLE_BUTTON (widget));
1340
1341         g_signal_handlers_block_by_func (widget, callback, user_data);
1342         g_object_set (widget, "active", active, NULL);
1343         g_signal_handlers_unblock_by_func (widget, callback, user_data);
1344 }
1345