]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-ui-utils.c
Completely reworked ContactList API. Fixes bug #471611, bug #467280, bug #459540...
[empathy.git] / libempathy-gtk / empathy-ui-utils.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  * Copyright (C) 2002-2007 Imendio AB
4  * Copyright (C) 2007 Collabora Ltd.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation; either version 2 of the
9  * License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public
17  * License along with this program; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  * 
21  * Authors: Mikael Hallendal <micke@imendio.com>
22  *          Richard Hult <richard@imendio.com>
23  *          Martyn Russell <martyn@imendio.com>
24  *          Xavier Claessens <xclaesse@gmail.com>
25  * 
26  *          Part of this file is copied from GtkSourceView (gtksourceiter.c):
27  *          Paolo Maggi
28  *          Jeroen Zwartepoorte
29  */
30
31 #include <string.h>
32 #include <X11/Xatom.h>
33 #include <gdk/gdkx.h>
34 #include <glib/gi18n.h>
35 #include <gtk/gtk.h>
36 #include <glade/glade.h>
37 #include <libgnomevfs/gnome-vfs-utils.h>
38
39 #include <libmissioncontrol/mc-profile.h>
40
41 #include <libempathy/empathy-debug.h>
42
43 #include "empathy-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 = g_build_filename (DATADIR, "empathy", filename, NULL);
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 empathy_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 empathy_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 empathy_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 empathy_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 empathy_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         gint           w, h;
212         gint           size = 48;
213
214         theme = gtk_icon_theme_get_default ();
215
216         if (gtk_icon_size_lookup (icon_size, &w, &h)) {
217                 size = (w + h) / 2;
218         }
219
220         pixbuf = gtk_icon_theme_load_icon (theme,
221                                            icon_name,
222                                            size,
223                                            0,
224                                            &error);
225         if (error) {
226                 empathy_debug (DEBUG_DOMAIN, "Error loading icon: %s", error->message);
227                 g_clear_error (&error);
228         }
229
230         return pixbuf;
231 }
232
233 GdkPixbuf *
234 empathy_pixbuf_from_smiley (EmpathySmiley type,
235                            GtkIconSize  icon_size)
236 {
237         const gchar *icon_id;
238
239         switch (type) {
240         case EMPATHY_SMILEY_NORMAL:       /*  :)   */
241                 icon_id = "stock_smiley-1";
242                 break;
243         case EMPATHY_SMILEY_WINK:         /*  ;)   */
244                 icon_id = "stock_smiley-3";
245                 break;
246         case EMPATHY_SMILEY_BIGEYE:       /*  =)   */
247                 icon_id = "stock_smiley-2";
248                 break;
249         case EMPATHY_SMILEY_NOSE:         /*  :-)  */
250                 icon_id = "stock_smiley-7";
251                 break;
252         case EMPATHY_SMILEY_CRY:          /*  :'(  */
253                 icon_id = "stock_smiley-11";
254                 break;
255         case EMPATHY_SMILEY_SAD:          /*  :(   */
256                 icon_id = "stock_smiley-4";
257                 break;
258         case EMPATHY_SMILEY_SCEPTICAL:    /*  :/   */
259                 icon_id = "stock_smiley-9";
260                 break;
261         case EMPATHY_SMILEY_BIGSMILE:     /*  :D   */
262                 icon_id = "stock_smiley-6";
263                 break;
264         case EMPATHY_SMILEY_INDIFFERENT:  /*  :|   */
265                 icon_id = "stock_smiley-8";
266                 break;
267         case EMPATHY_SMILEY_TOUNGE:       /*  :p   */
268                 icon_id = "stock_smiley-10";
269                 break;
270         case EMPATHY_SMILEY_SHOCKED:      /*  :o   */
271                 icon_id = "stock_smiley-5";
272                 break;
273         case EMPATHY_SMILEY_COOL:         /*  8)   */
274                 icon_id = "stock_smiley-15";
275                 break;
276         case EMPATHY_SMILEY_SORRY:        /*  *|   */
277                 icon_id = "stock_smiley-12";
278                 break;
279         case EMPATHY_SMILEY_KISS:         /*  :*   */
280                 icon_id = "stock_smiley-13";
281                 break;
282         case EMPATHY_SMILEY_SHUTUP:       /*  :#   */
283                 icon_id = "stock_smiley-14";
284                 break;
285         case EMPATHY_SMILEY_YAWN:         /*  |O   */
286                 icon_id = "";
287                 break;
288         case EMPATHY_SMILEY_CONFUSED:     /*  :$   */
289                 icon_id = "stock_smiley-17";
290                 break;
291         case EMPATHY_SMILEY_ANGEL:        /*  O)   */
292                 icon_id = "stock_smiley-18";
293                 break;
294         case EMPATHY_SMILEY_OOOH:         /*  :x   */
295                 icon_id = "stock_smiley-19";
296                 break;
297         case EMPATHY_SMILEY_LOOKAWAY:     /*  *)   */
298                 icon_id = "stock_smiley-20";
299                 break;
300         case EMPATHY_SMILEY_BLUSH:        /*  *S   */
301                 icon_id = "stock_smiley-23";
302                 break;
303         case EMPATHY_SMILEY_COOLBIGSMILE: /*  8D   */
304                 icon_id = "stock_smiley-25";
305                 break;
306         case EMPATHY_SMILEY_ANGRY:        /*  :@   */
307                 icon_id = "stock_smiley-16";
308                 break;
309         case EMPATHY_SMILEY_BOSS:         /*  @)   */
310                 icon_id = "stock_smiley-21";
311                 break;
312         case EMPATHY_SMILEY_MONKEY:       /*  #)   */
313                 icon_id = "stock_smiley-22";
314                 break;
315         case EMPATHY_SMILEY_SILLY:        /*  O)   */
316                 icon_id = "stock_smiley-24";
317                 break;
318         case EMPATHY_SMILEY_SICK:         /*  +o(  */
319                 icon_id = "stock_smiley-26";
320                 break;
321
322         default:
323                 g_assert_not_reached ();
324                 icon_id = NULL;
325         }
326
327
328         return empathy_pixbuf_from_icon_name (icon_id, icon_size);
329 }
330
331 const gchar *
332 empathy_icon_name_from_account (McAccount *account)
333 {
334         McProfile *profile;
335
336         profile = mc_account_get_profile (account);
337
338         return mc_profile_get_icon_name (profile);
339 }
340
341 const gchar *
342 empathy_icon_name_for_presence_state (McPresence state)
343 {
344         switch (state) {
345         case MC_PRESENCE_AVAILABLE:
346                 return EMPATHY_IMAGE_AVAILABLE;
347         case MC_PRESENCE_DO_NOT_DISTURB:
348                 return EMPATHY_IMAGE_BUSY;
349         case MC_PRESENCE_AWAY:
350                 return EMPATHY_IMAGE_AWAY;
351         case MC_PRESENCE_EXTENDED_AWAY:
352                 return EMPATHY_IMAGE_EXT_AWAY;
353         case MC_PRESENCE_HIDDEN:
354                 return EMPATHY_IMAGE_HIDDEN;
355         case MC_PRESENCE_OFFLINE:
356         case MC_PRESENCE_UNSET:
357                 return EMPATHY_IMAGE_OFFLINE;
358         default:
359                 g_assert_not_reached ();
360         }
361
362         return NULL;
363 }
364
365 const gchar *
366 empathy_icon_name_for_presence (EmpathyPresence *presence)
367 {
368         McPresence state;
369
370         g_return_val_if_fail (EMPATHY_IS_PRESENCE (presence),
371                               EMPATHY_IMAGE_OFFLINE);
372
373         state = empathy_presence_get_state (presence);
374
375         return empathy_icon_name_for_presence_state (state);
376 }
377
378 const gchar *
379 empathy_icon_name_for_contact (EmpathyContact *contact)
380 {
381         EmpathyPresence *presence;
382
383         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact),
384                               EMPATHY_IMAGE_OFFLINE);
385
386         presence = empathy_contact_get_presence (contact);
387         if (presence) {
388                 return empathy_icon_name_for_presence (presence);
389         }
390
391         return EMPATHY_IMAGE_UNKNOWN;
392 }
393
394 static void
395 pixbuf_from_avatar_size_prepared_cb (GdkPixbufLoader *loader,
396                                      int              width,
397                                      int              height,
398                                      struct SizeData *data)
399 {
400         g_return_if_fail (width > 0 && height > 0);
401
402         if (data->preserve_aspect_ratio && (data->width > 0 || data->height > 0)) {
403                 if (width < data->width && height < data->height) {
404                         width = width;
405                         height = height;
406                 }
407
408                 if (data->width < 0) {
409                         width = width * (double) data->height / (gdouble) height;
410                         height = data->height;
411                 } else if (data->height < 0) {
412                         height = height * (double) data->width / (double) width;
413                         width = data->width;
414                 } else if ((double) height * (double) data->width >
415                            (double) width * (double) data->height) {
416                         width = 0.5 + (double) width * (double) data->height / (double) height;
417                         height = data->height;
418                 } else {
419                         height = 0.5 + (double) height * (double) data->width / (double) width;
420                         width = data->width;
421                 }
422         } else {
423                 if (data->width > 0) {
424                         width = data->width;
425                 }
426
427                 if (data->height > 0) {
428                         height = data->height;
429                 }
430         }
431
432         gdk_pixbuf_loader_set_size (loader, width, height);
433 }
434
435 static void
436 empathy_avatar_pixbuf_roundify (GdkPixbuf *pixbuf)
437 {
438         gint width, height, rowstride;
439         guchar *pixels;
440
441         width = gdk_pixbuf_get_width (pixbuf);
442         height = gdk_pixbuf_get_height (pixbuf);
443         rowstride = gdk_pixbuf_get_rowstride (pixbuf);
444         pixels = gdk_pixbuf_get_pixels (pixbuf);
445
446         if (width < 6 || height < 6) {
447                 return;
448         }
449
450         /* Top left */
451         pixels[3] = 0;
452         pixels[7] = 0x80;
453         pixels[11] = 0xC0;
454         pixels[rowstride + 3] = 0x80;
455         pixels[rowstride * 2 + 3] = 0xC0;
456
457         /* Top right */
458         pixels[width * 4 - 1] = 0;
459         pixels[width * 4 - 5] = 0x80;
460         pixels[width * 4 - 9] = 0xC0;
461         pixels[rowstride + (width * 4) - 1] = 0x80;
462         pixels[(2 * rowstride) + (width * 4) - 1] = 0xC0;
463
464         /* Bottom left */
465         pixels[(height - 1) * rowstride + 3] = 0;
466         pixels[(height - 1) * rowstride + 7] = 0x80;
467         pixels[(height - 1) * rowstride + 11] = 0xC0;
468         pixels[(height - 2) * rowstride + 3] = 0x80;
469         pixels[(height - 3) * rowstride + 3] = 0xC0;
470
471         /* Bottom right */
472         pixels[height * rowstride - 1] = 0;
473         pixels[(height - 1) * rowstride - 1] = 0x80;
474         pixels[(height - 2) * rowstride - 1] = 0xC0;
475         pixels[height * rowstride - 5] = 0x80;
476         pixels[height * rowstride - 9] = 0xC0;
477 }
478
479 static gboolean
480 empathy_gdk_pixbuf_is_opaque (GdkPixbuf *pixbuf)
481 {
482         gint width, height, rowstride, i;
483         guchar *pixels;
484         guchar *row;
485
486         width = gdk_pixbuf_get_width (pixbuf);
487         height = gdk_pixbuf_get_height (pixbuf);
488         rowstride = gdk_pixbuf_get_rowstride (pixbuf);
489         pixels = gdk_pixbuf_get_pixels (pixbuf);
490
491         row = pixels;
492         for (i = 3; i < rowstride; i+=4) {
493                 if (row[i] < 0xfe) {
494                         return FALSE;
495                 }
496         }
497
498         for (i = 1; i < height - 1; i++) {
499                 row = pixels + (i*rowstride);
500                 if (row[3] < 0xfe || row[rowstride-1] < 0xfe) {
501                         return FALSE;
502                 }
503         }
504
505         row = pixels + ((height-1) * rowstride);
506         for (i = 3; i < rowstride; i+=4) {
507                 if (row[i] < 0xfe) {
508                         return FALSE;
509                 }
510         }
511
512         return TRUE;
513 }
514
515 GdkPixbuf *
516 empathy_pixbuf_from_avatar_scaled (EmpathyAvatar *avatar,
517                                   gint          width,
518                                   gint          height)
519 {
520         GdkPixbuf        *pixbuf;
521         GdkPixbufLoader  *loader;
522         struct SizeData   data;
523         GError           *error = NULL;
524
525         if (!avatar) {
526                 return NULL;
527         }
528
529         data.width = width;
530         data.height = height;
531         data.preserve_aspect_ratio = TRUE;
532
533         loader = gdk_pixbuf_loader_new ();
534
535         g_signal_connect (loader, "size-prepared",
536                           G_CALLBACK (pixbuf_from_avatar_size_prepared_cb),
537                           &data);
538
539         if (!gdk_pixbuf_loader_write (loader, avatar->data, avatar->len, &error)) {
540                 g_warning ("Couldn't write avatar image:%p with "
541                            "length:%" G_GSIZE_FORMAT " to pixbuf loader: %s",
542                            avatar->data, avatar->len, error->message);
543                 g_error_free (error);
544                 return NULL;
545         }
546
547         gdk_pixbuf_loader_close (loader, NULL);
548
549         pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
550         if (!gdk_pixbuf_get_has_alpha (pixbuf)) {
551                 GdkPixbuf *rounded_pixbuf;
552
553                 rounded_pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8,
554                                                  gdk_pixbuf_get_width (pixbuf),
555                                                  gdk_pixbuf_get_height (pixbuf));
556                 gdk_pixbuf_copy_area (pixbuf, 0, 0,
557                                       gdk_pixbuf_get_width (pixbuf),
558                                       gdk_pixbuf_get_height (pixbuf),
559                                       rounded_pixbuf,
560                                       0, 0);
561                 pixbuf = rounded_pixbuf;
562         } else {
563                 g_object_ref (pixbuf);
564         }
565
566         if (empathy_gdk_pixbuf_is_opaque (pixbuf)) {
567                 empathy_avatar_pixbuf_roundify (pixbuf);
568         }
569
570         g_object_unref (loader);
571
572         return pixbuf;
573 }
574
575 GdkPixbuf *
576 empathy_pixbuf_avatar_from_contact_scaled (EmpathyContact *contact,
577                                           gint           width,
578                                           gint           height)
579 {
580         EmpathyAvatar *avatar;
581
582         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
583
584         avatar = empathy_contact_get_avatar (contact);
585
586         return empathy_pixbuf_from_avatar_scaled (avatar, width, height);
587 }
588
589 /* Stolen from GtkSourceView, hence the weird intendation. Please keep it like
590  * that to make it easier to apply changes from the original code.
591  */
592 #define GTK_TEXT_UNKNOWN_CHAR 0xFFFC
593
594 /* this function acts like g_utf8_offset_to_pointer() except that if it finds a
595  * decomposable character it consumes the decomposition length from the given
596  * offset.  So it's useful when the offset was calculated for the normalized
597  * version of str, but we need a pointer to str itself. */
598 static const gchar *
599 pointer_from_offset_skipping_decomp (const gchar *str, gint offset)
600 {
601         gchar *casefold, *normal;
602         const gchar *p, *q;
603
604         p = str;
605         while (offset > 0)
606         {
607                 q = g_utf8_next_char (p);
608                 casefold = g_utf8_casefold (p, q - p);
609                 normal = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
610                 offset -= g_utf8_strlen (normal, -1);
611                 g_free (casefold);
612                 g_free (normal);
613                 p = q;
614         }
615         return p;
616 }
617
618 static const gchar *
619 g_utf8_strcasestr (const gchar *haystack, const gchar *needle)
620 {
621         gsize needle_len;
622         gsize haystack_len;
623         const gchar *ret = NULL;
624         gchar *p;
625         gchar *casefold;
626         gchar *caseless_haystack;
627         gint i;
628
629         g_return_val_if_fail (haystack != NULL, NULL);
630         g_return_val_if_fail (needle != NULL, NULL);
631
632         casefold = g_utf8_casefold (haystack, -1);
633         caseless_haystack = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
634         g_free (casefold);
635
636         needle_len = g_utf8_strlen (needle, -1);
637         haystack_len = g_utf8_strlen (caseless_haystack, -1);
638
639         if (needle_len == 0)
640         {
641                 ret = (gchar *)haystack;
642                 goto finally_1;
643         }
644
645         if (haystack_len < needle_len)
646         {
647                 ret = NULL;
648                 goto finally_1;
649         }
650
651         p = (gchar*)caseless_haystack;
652         needle_len = strlen (needle);
653         i = 0;
654
655         while (*p)
656         {
657                 if ((strncmp (p, needle, needle_len) == 0))
658                 {
659                         ret = pointer_from_offset_skipping_decomp (haystack, i);
660                         goto finally_1;
661                 }
662
663                 p = g_utf8_next_char (p);
664                 i++;
665         }
666
667 finally_1:
668         g_free (caseless_haystack);
669
670         return ret;
671 }
672
673 static gboolean
674 g_utf8_caselessnmatch (const char *s1, const char *s2,
675                        gssize n1, gssize n2)
676 {
677         gchar *casefold;
678         gchar *normalized_s1;
679         gchar *normalized_s2;
680         gint len_s1;
681         gint len_s2;
682         gboolean ret = FALSE;
683
684         g_return_val_if_fail (s1 != NULL, FALSE);
685         g_return_val_if_fail (s2 != NULL, FALSE);
686         g_return_val_if_fail (n1 > 0, FALSE);
687         g_return_val_if_fail (n2 > 0, FALSE);
688
689         casefold = g_utf8_casefold (s1, n1);
690         normalized_s1 = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
691         g_free (casefold);
692
693         casefold = g_utf8_casefold (s2, n2);
694         normalized_s2 = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
695         g_free (casefold);
696
697         len_s1 = strlen (normalized_s1);
698         len_s2 = strlen (normalized_s2);
699
700         if (len_s1 < len_s2)
701                 goto finally_2;
702
703         ret = (strncmp (normalized_s1, normalized_s2, len_s2) == 0);
704
705 finally_2:
706         g_free (normalized_s1);
707         g_free (normalized_s2);
708
709         return ret;
710 }
711
712 static void
713 forward_chars_with_skipping (GtkTextIter *iter,
714                              gint         count,
715                              gboolean     skip_invisible,
716                              gboolean     skip_nontext,
717                              gboolean     skip_decomp)
718 {
719         gint i;
720
721         g_return_if_fail (count >= 0);
722
723         i = count;
724
725         while (i > 0)
726         {
727                 gboolean ignored = FALSE;
728
729                 /* minimal workaround to avoid the infinite loop of bug #168247.
730                  * It doesn't fix the problemjust the symptom...
731                  */
732                 if (gtk_text_iter_is_end (iter))
733                         return;
734
735                 if (skip_nontext && gtk_text_iter_get_char (iter) == GTK_TEXT_UNKNOWN_CHAR)
736                         ignored = TRUE;
737
738                 if (!ignored && skip_invisible &&
739                     /* _gtk_text_btree_char_is_invisible (iter)*/ FALSE)
740                         ignored = TRUE;
741
742                 if (!ignored && skip_decomp)
743                 {
744                         /* being UTF8 correct sucks; this accounts for extra
745                            offsets coming from canonical decompositions of
746                            UTF8 characters (e.g. accented characters) which
747                            g_utf8_normalize() performs */
748                         gchar *normal;
749                         gchar buffer[6];
750                         gint buffer_len;
751
752                         buffer_len = g_unichar_to_utf8 (gtk_text_iter_get_char (iter), buffer);
753                         normal = g_utf8_normalize (buffer, buffer_len, G_NORMALIZE_NFD);
754                         i -= (g_utf8_strlen (normal, -1) - 1);
755                         g_free (normal);
756                 }
757
758                 gtk_text_iter_forward_char (iter);
759
760                 if (!ignored)
761                         --i;
762         }
763 }
764
765 static gboolean
766 lines_match (const GtkTextIter *start,
767              const gchar      **lines,
768              gboolean           visible_only,
769              gboolean           slice,
770              GtkTextIter       *match_start,
771              GtkTextIter       *match_end)
772 {
773         GtkTextIter next;
774         gchar *line_text;
775         const gchar *found;
776         gint offset;
777
778         if (*lines == NULL || **lines == '\0')
779         {
780                 if (match_start)
781                         *match_start = *start;
782                 if (match_end)
783                         *match_end = *start;
784                 return TRUE;
785         }
786
787         next = *start;
788         gtk_text_iter_forward_line (&next);
789
790         /* No more text in buffer, but *lines is nonempty */
791         if (gtk_text_iter_equal (start, &next))
792                 return FALSE;
793
794         if (slice)
795         {
796                 if (visible_only)
797                         line_text = gtk_text_iter_get_visible_slice (start, &next);
798                 else
799                         line_text = gtk_text_iter_get_slice (start, &next);
800         }
801         else
802         {
803                 if (visible_only)
804                         line_text = gtk_text_iter_get_visible_text (start, &next);
805                 else
806                         line_text = gtk_text_iter_get_text (start, &next);
807         }
808
809         if (match_start) /* if this is the first line we're matching */
810         {
811                 found = g_utf8_strcasestr (line_text, *lines);
812         }
813         else
814         {
815                 /* If it's not the first line, we have to match from the
816                  * start of the line.
817                  */
818                 if (g_utf8_caselessnmatch (line_text, *lines, strlen (line_text),
819                                            strlen (*lines)))
820                         found = line_text;
821                 else
822                         found = NULL;
823         }
824
825         if (found == NULL)
826         {
827                 g_free (line_text);
828                 return FALSE;
829         }
830
831         /* Get offset to start of search string */
832         offset = g_utf8_strlen (line_text, found - line_text);
833
834         next = *start;
835
836         /* If match start needs to be returned, set it to the
837          * start of the search string.
838          */
839         forward_chars_with_skipping (&next, offset, visible_only, !slice, FALSE);
840         if (match_start)
841         {
842                 *match_start = next;
843         }
844
845         /* Go to end of search string */
846         forward_chars_with_skipping (&next, g_utf8_strlen (*lines, -1), visible_only, !slice, TRUE);
847
848         g_free (line_text);
849
850         ++lines;
851
852         if (match_end)
853                 *match_end = next;
854
855         /* pass NULL for match_start, since we don't need to find the
856          * start again.
857          */
858         return lines_match (&next, lines, visible_only, slice, NULL, match_end);
859 }
860
861 /* strsplit () that retains the delimiter as part of the string. */
862 static gchar **
863 strbreakup (const char *string,
864             const char *delimiter,
865             gint        max_tokens)
866 {
867         GSList *string_list = NULL, *slist;
868         gchar **str_array, *s, *casefold, *new_string;
869         guint i, n = 1;
870
871         g_return_val_if_fail (string != NULL, NULL);
872         g_return_val_if_fail (delimiter != NULL, NULL);
873
874         if (max_tokens < 1)
875                 max_tokens = G_MAXINT;
876
877         s = strstr (string, delimiter);
878         if (s)
879         {
880                 guint delimiter_len = strlen (delimiter);
881
882                 do
883                 {
884                         guint len;
885
886                         len = s - string + delimiter_len;
887                         new_string = g_new (gchar, len + 1);
888                         strncpy (new_string, string, len);
889                         new_string[len] = 0;
890                         casefold = g_utf8_casefold (new_string, -1);
891                         g_free (new_string);
892                         new_string = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
893                         g_free (casefold);
894                         string_list = g_slist_prepend (string_list, new_string);
895                         n++;
896                         string = s + delimiter_len;
897                         s = strstr (string, delimiter);
898                 } while (--max_tokens && s);
899         }
900
901         if (*string)
902         {
903                 n++;
904                 casefold = g_utf8_casefold (string, -1);
905                 new_string = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
906                 g_free (casefold);
907                 string_list = g_slist_prepend (string_list, new_string);
908         }
909
910         str_array = g_new (gchar*, n);
911
912         i = n - 1;
913
914         str_array[i--] = NULL;
915         for (slist = string_list; slist; slist = slist->next)
916                 str_array[i--] = slist->data;
917
918         g_slist_free (string_list);
919
920         return str_array;
921 }
922
923 gboolean
924 empathy_text_iter_forward_search (const GtkTextIter   *iter,
925                                  const gchar         *str,
926                                  GtkTextIter         *match_start,
927                                  GtkTextIter         *match_end,
928                                  const GtkTextIter   *limit)
929 {
930         gchar **lines = NULL;
931         GtkTextIter match;
932         gboolean retval = FALSE;
933         GtkTextIter search;
934         gboolean visible_only;
935         gboolean slice;
936
937         g_return_val_if_fail (iter != NULL, FALSE);
938         g_return_val_if_fail (str != NULL, FALSE);
939
940         if (limit && gtk_text_iter_compare (iter, limit) >= 0)
941                 return FALSE;
942
943         if (*str == '\0') {
944                 /* If we can move one char, return the empty string there */
945                 match = *iter;
946
947                 if (gtk_text_iter_forward_char (&match)) {
948                         if (limit && gtk_text_iter_equal (&match, limit)) {
949                                 return FALSE;
950                         }
951
952                         if (match_start) {
953                                 *match_start = match;
954                         }
955                         if (match_end) {
956                                 *match_end = match;
957                         }
958                         return TRUE;
959                 } else {
960                         return FALSE;
961                 }
962         }
963
964         visible_only = TRUE;
965         slice = FALSE;
966
967         /* locate all lines */
968         lines = strbreakup (str, "\n", -1);
969
970         search = *iter;
971
972         do {
973                 /* This loop has an inefficient worst-case, where
974                  * gtk_text_iter_get_text () is called repeatedly on
975                  * a single line.
976                  */
977                 GtkTextIter end;
978
979                 if (limit && gtk_text_iter_compare (&search, limit) >= 0) {
980                         break;
981                 }
982
983                 if (lines_match (&search, (const gchar**)lines,
984                                  visible_only, slice, &match, &end)) {
985                         if (limit == NULL ||
986                             (limit && gtk_text_iter_compare (&end, limit) <= 0)) {
987                                 retval = TRUE;
988
989                                 if (match_start) {
990                                         *match_start = match;
991                                 }
992                                 if (match_end) {
993                                         *match_end = end;
994                                 }
995                         }
996                         break;
997                 }
998         } while (gtk_text_iter_forward_line (&search));
999
1000         g_strfreev ((gchar**)lines);
1001
1002         return retval;
1003 }
1004
1005 static const gchar *
1006 g_utf8_strrcasestr (const gchar *haystack, const gchar *needle)
1007 {
1008         gsize needle_len;
1009         gsize haystack_len;
1010         const gchar *ret = NULL;
1011         gchar *p;
1012         gchar *casefold;
1013         gchar *caseless_haystack;
1014         gint i;
1015
1016         g_return_val_if_fail (haystack != NULL, NULL);
1017         g_return_val_if_fail (needle != NULL, NULL);
1018
1019         casefold = g_utf8_casefold (haystack, -1);
1020         caseless_haystack = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1021         g_free (casefold);
1022
1023         needle_len = g_utf8_strlen (needle, -1);
1024         haystack_len = g_utf8_strlen (caseless_haystack, -1);
1025
1026         if (needle_len == 0)
1027         {
1028                 ret = (gchar *)haystack;
1029                 goto finally_1;
1030         }
1031
1032         if (haystack_len < needle_len)
1033         {
1034                 ret = NULL;
1035                 goto finally_1;
1036         }
1037
1038         i = haystack_len - needle_len;
1039         p = g_utf8_offset_to_pointer (caseless_haystack, i);
1040         needle_len = strlen (needle);
1041
1042         while (p >= caseless_haystack)
1043         {
1044                 if (strncmp (p, needle, needle_len) == 0)
1045                 {
1046                         ret = pointer_from_offset_skipping_decomp (haystack, i);
1047                         goto finally_1;
1048                 }
1049
1050                 p = g_utf8_prev_char (p);
1051                 i--;
1052         }
1053
1054 finally_1:
1055         g_free (caseless_haystack);
1056
1057         return ret;
1058 }
1059
1060 static gboolean
1061 backward_lines_match (const GtkTextIter *start,
1062                       const gchar      **lines,
1063                       gboolean           visible_only,
1064                       gboolean           slice,
1065                       GtkTextIter       *match_start,
1066                       GtkTextIter       *match_end)
1067 {
1068         GtkTextIter line, next;
1069         gchar *line_text;
1070         const gchar *found;
1071         gint offset;
1072
1073         if (*lines == NULL || **lines == '\0')
1074         {
1075                 if (match_start)
1076                         *match_start = *start;
1077                 if (match_end)
1078                         *match_end = *start;
1079                 return TRUE;
1080         }
1081
1082         line = next = *start;
1083         if (gtk_text_iter_get_line_offset (&next) == 0)
1084         {
1085                 if (!gtk_text_iter_backward_line (&next))
1086                         return FALSE;
1087         }
1088         else
1089                 gtk_text_iter_set_line_offset (&next, 0);
1090
1091         if (slice)
1092         {
1093                 if (visible_only)
1094                         line_text = gtk_text_iter_get_visible_slice (&next, &line);
1095                 else
1096                         line_text = gtk_text_iter_get_slice (&next, &line);
1097         }
1098         else
1099         {
1100                 if (visible_only)
1101                         line_text = gtk_text_iter_get_visible_text (&next, &line);
1102                 else
1103                         line_text = gtk_text_iter_get_text (&next, &line);
1104         }
1105
1106         if (match_start) /* if this is the first line we're matching */
1107         {
1108                 found = g_utf8_strrcasestr (line_text, *lines);
1109         }
1110         else
1111         {
1112                 /* If it's not the first line, we have to match from the
1113                  * start of the line.
1114                  */
1115                 if (g_utf8_caselessnmatch (line_text, *lines, strlen (line_text),
1116                                            strlen (*lines)))
1117                         found = line_text;
1118                 else
1119                         found = NULL;
1120         }
1121
1122         if (found == NULL)
1123         {
1124                 g_free (line_text);
1125                 return FALSE;
1126         }
1127
1128         /* Get offset to start of search string */
1129         offset = g_utf8_strlen (line_text, found - line_text);
1130
1131         forward_chars_with_skipping (&next, offset, visible_only, !slice, FALSE);
1132
1133         /* If match start needs to be returned, set it to the
1134          * start of the search string.
1135          */
1136         if (match_start)
1137         {
1138                 *match_start = next;
1139         }
1140
1141         /* Go to end of search string */
1142         forward_chars_with_skipping (&next, g_utf8_strlen (*lines, -1), visible_only, !slice, TRUE);
1143
1144         g_free (line_text);
1145
1146         ++lines;
1147
1148         if (match_end)
1149                 *match_end = next;
1150
1151         /* try to match the rest of the lines forward, passing NULL
1152          * for match_start so lines_match will try to match the entire
1153          * line */
1154         return lines_match (&next, lines, visible_only,
1155                             slice, NULL, match_end);
1156 }
1157
1158 gboolean
1159 empathy_text_iter_backward_search (const GtkTextIter   *iter,
1160                                   const gchar         *str,
1161                                   GtkTextIter         *match_start,
1162                                   GtkTextIter         *match_end,
1163                                   const GtkTextIter   *limit)
1164 {
1165         gchar **lines = NULL;
1166         GtkTextIter match;
1167         gboolean retval = FALSE;
1168         GtkTextIter search;
1169         gboolean visible_only;
1170         gboolean slice;
1171
1172         g_return_val_if_fail (iter != NULL, FALSE);
1173         g_return_val_if_fail (str != NULL, FALSE);
1174
1175         if (limit && gtk_text_iter_compare (iter, limit) <= 0)
1176                 return FALSE;
1177
1178         if (*str == '\0')
1179         {
1180                 /* If we can move one char, return the empty string there */
1181                 match = *iter;
1182
1183                 if (gtk_text_iter_backward_char (&match))
1184                 {
1185                         if (limit && gtk_text_iter_equal (&match, limit))
1186                                 return FALSE;
1187
1188                         if (match_start)
1189                                 *match_start = match;
1190                         if (match_end)
1191                                 *match_end = match;
1192                         return TRUE;
1193                 }
1194                 else
1195                 {
1196                         return FALSE;
1197                 }
1198         }
1199
1200         visible_only = TRUE;
1201         slice = TRUE;
1202
1203         /* locate all lines */
1204         lines = strbreakup (str, "\n", -1);
1205
1206         search = *iter;
1207
1208         while (TRUE)
1209         {
1210                 /* This loop has an inefficient worst-case, where
1211                  * gtk_text_iter_get_text () is called repeatedly on
1212                  * a single line.
1213                  */
1214                 GtkTextIter end;
1215
1216                 if (limit && gtk_text_iter_compare (&search, limit) <= 0)
1217                         break;
1218
1219                 if (backward_lines_match (&search, (const gchar**)lines,
1220                                           visible_only, slice, &match, &end))
1221                 {
1222                         if (limit == NULL || (limit &&
1223                                               gtk_text_iter_compare (&end, limit) > 0))
1224                         {
1225                                 retval = TRUE;
1226
1227                                 if (match_start)
1228                                         *match_start = match;
1229                                 if (match_end)
1230                                         *match_end = end;
1231                         }
1232                         break;
1233                 }
1234
1235                 if (gtk_text_iter_get_line_offset (&search) == 0)
1236                 {
1237                         if (!gtk_text_iter_backward_line (&search))
1238                                 break;
1239                 }
1240                 else
1241                 {
1242                         gtk_text_iter_set_line_offset (&search, 0);
1243                 }
1244         }
1245
1246         g_strfreev ((gchar**)lines);
1247
1248         return retval;
1249 }
1250
1251 static gboolean
1252 window_get_is_on_current_workspace (GtkWindow *window)
1253 {
1254         GdkWindow *gdk_window;
1255
1256         gdk_window = GTK_WIDGET (window)->window;
1257         if (gdk_window) {
1258                 return !(gdk_window_get_state (gdk_window) &
1259                          GDK_WINDOW_STATE_ICONIFIED);
1260         } else {
1261                 return FALSE;
1262         }
1263 }
1264
1265 /* Checks if the window is visible as in visible on the current workspace. */
1266 gboolean
1267 empathy_window_get_is_visible (GtkWindow *window)
1268 {
1269         g_return_val_if_fail (GTK_IS_WINDOW (window), FALSE);
1270
1271         return GTK_WIDGET_VISIBLE (GTK_WIDGET (window)) &&
1272                window_get_is_on_current_workspace (window);
1273 }
1274
1275 void 
1276 empathy_window_iconify (GtkWindow *window, GtkStatusIcon *status_icon)
1277 {
1278         GdkRectangle  icon_location;
1279         gulong        data[4];
1280         Display      *dpy;
1281         GdkWindow    *gdk_window;
1282
1283         gtk_status_icon_get_geometry (status_icon, NULL, &icon_location, NULL);
1284         gdk_window = GTK_WIDGET (window)->window;
1285         dpy = gdk_x11_drawable_get_xdisplay (gdk_window);
1286
1287         data[0] = icon_location.x;
1288         data[1] = icon_location.y;
1289         data[2] = icon_location.width;
1290         data[3] = icon_location.height;
1291
1292         XChangeProperty (dpy,
1293                          GDK_WINDOW_XID (gdk_window),
1294                          gdk_x11_get_xatom_by_name_for_display (gdk_drawable_get_display (gdk_window),
1295                                                                 "_NET_WM_ICON_GEOMETRY"),
1296                          XA_CARDINAL, 32, PropModeReplace,
1297                          (guchar *)&data, 4);
1298
1299         gtk_window_set_skip_taskbar_hint (window, TRUE);
1300         gtk_window_iconify (window);
1301
1302 }
1303
1304 /* Takes care of moving the window to the current workspace. */
1305 void
1306 empathy_window_present (GtkWindow *window,
1307                        gboolean   steal_focus)
1308 {
1309         gboolean on_current;
1310         guint32  timestamp;
1311
1312         g_return_if_fail (window != NULL);
1313
1314         /* There are three cases: hidden, visible, visible on another
1315          * workspace.
1316          */
1317
1318         on_current = window_get_is_on_current_workspace (window);
1319
1320         if ( GTK_WIDGET_VISIBLE (GTK_WIDGET (window)) && !on_current) {
1321                 /* Hide it so present brings it to the current workspace. */
1322                 gtk_widget_hide (GTK_WIDGET (window));
1323         }
1324
1325         gtk_window_set_skip_taskbar_hint (window, FALSE);
1326
1327         timestamp = gtk_get_current_event_time ();
1328         if (steal_focus && timestamp != GDK_CURRENT_TIME) {
1329                 gtk_window_present_with_time (window, timestamp);
1330         } else {
1331                 gtk_window_present (window);
1332         }
1333 }
1334
1335 GtkWindow *
1336 empathy_get_toplevel_window (GtkWidget *widget)
1337 {
1338         GtkWidget *toplevel;
1339
1340         g_return_val_if_fail (GTK_IS_WIDGET (widget), NULL);
1341
1342         toplevel = gtk_widget_get_toplevel (widget);
1343         if (GTK_IS_WINDOW (toplevel) &&
1344             GTK_WIDGET_TOPLEVEL (toplevel)) {
1345                 return GTK_WINDOW (toplevel);
1346         }
1347
1348         return NULL;
1349 }
1350
1351 /* The URL opening code can't handle schemeless strings, so we try to be
1352  * smart and add http if there is no scheme or doesn't look like a mail
1353  * address. This should work in most cases, and let us click on strings
1354  * like "www.gnome.org".
1355  */
1356 static gchar *
1357 fixup_url (const gchar *url)
1358 {
1359         gchar *real_url;
1360
1361         if (!g_str_has_prefix (url, "http://") &&
1362             !strstr (url, ":/") &&
1363             !strstr (url, "@")) {
1364                 real_url = g_strdup_printf ("http://%s", url);
1365         } else {
1366                 real_url = g_strdup (url);
1367         }
1368
1369         return real_url;
1370 }
1371
1372 void
1373 empathy_url_show (const char *url)
1374 {
1375         gchar          *real_url;
1376         GnomeVFSResult  res;
1377
1378         real_url = fixup_url (url);
1379         res = gnome_vfs_url_show (real_url);
1380         if (res != GNOME_VFS_OK) {
1381                 empathy_debug (DEBUG_DOMAIN, "Couldn't show URL %s: %s",
1382                               real_url,
1383                               gnome_vfs_result_to_string (res));
1384         }
1385
1386         g_free (real_url);
1387 }
1388
1389 static void
1390 link_button_hook (GtkLinkButton *button,
1391                   const gchar *link,
1392                   gpointer user_data)
1393 {
1394         empathy_url_show (link);
1395 }
1396
1397 GtkWidget *
1398 empathy_link_button_new (const gchar *url,
1399                         const gchar *title)
1400 {
1401         static gboolean hook = FALSE;
1402
1403         if (!hook) {
1404                 hook = TRUE;
1405                 gtk_link_button_set_uri_hook (link_button_hook, NULL, NULL);
1406         }
1407
1408         return gtk_link_button_new_with_label (url, title);
1409 }
1410
1411 void
1412 empathy_toggle_button_set_state_quietly (GtkWidget *widget,
1413                                         GCallback  callback,
1414                                         gpointer   user_data,
1415                                         gboolean   active)
1416 {
1417         g_return_if_fail (GTK_IS_TOGGLE_BUTTON (widget));
1418
1419         g_signal_handlers_block_by_func (widget, callback, user_data);
1420         g_object_set (widget, "active", active, NULL);
1421         g_signal_handlers_unblock_by_func (widget, callback, user_data);
1422 }
1423