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