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