]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-ui-utils.c
Create a constructor for PixbufAvatarFromIndividualClosure.
[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-2010 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., 51 Franklin St, Fifth Floor,
19  * Boston, MA  02110-1301  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  *          Jonny Lamb <jonny.lamb@collabora.co.uk>
26  *          Travis Reitter <travis.reitter@collabora.co.uk>
27  *
28  *          Part of this file is copied from GtkSourceView (gtksourceiter.c):
29  *          Paolo Maggi
30  *          Jeroen Zwartepoorte
31  */
32
33 #include <config.h>
34
35 #include <string.h>
36 #include <X11/Xatom.h>
37 #include <gdk/gdkx.h>
38 #include <glib/gi18n-lib.h>
39 #include <gtk/gtk.h>
40 #include <gio/gio.h>
41
42 #include <folks/folks.h>
43
44 #include "empathy-ui-utils.h"
45 #include "empathy-images.h"
46 #include "empathy-smiley-manager.h"
47
48 #define DEBUG_FLAG EMPATHY_DEBUG_OTHER
49 #include <libempathy/empathy-debug.h>
50 #include <libempathy/empathy-utils.h>
51 #include <libempathy/empathy-dispatcher.h>
52 #include <libempathy/empathy-idle.h>
53 #include <libempathy/empathy-ft-factory.h>
54
55 void
56 empathy_gtk_init (void)
57 {
58         static gboolean initialized = FALSE;
59
60         if (initialized)
61                 return;
62
63         empathy_init ();
64         gtk_icon_theme_append_search_path (gtk_icon_theme_get_default (),
65                                            PKGDATADIR G_DIR_SEPARATOR_S "icons");
66
67         initialized = TRUE;
68 }
69
70 static GtkBuilder *
71 builder_get_file_valist (const gchar *filename,
72                          const gchar *first_object,
73                          va_list      args)
74 {
75         GtkBuilder  *gui;
76         const gchar *name;
77         GObject    **object_ptr;
78         GError      *error = NULL;
79
80         DEBUG ("Loading file %s", filename);
81
82         gui = gtk_builder_new ();
83         gtk_builder_set_translation_domain (gui, GETTEXT_PACKAGE);
84         if (!gtk_builder_add_from_file (gui, filename, &error)) {
85                 g_critical ("GtkBuilder Error (%s): %s",
86                                 filename, error->message);
87                 g_clear_error (&error);
88                 g_object_unref (gui);
89
90                 /* we need to iterate and set all of the pointers to NULL */
91                 for (name = first_object; name;
92                      name = va_arg (args, const gchar *)) {
93                         object_ptr = va_arg (args, GObject**);
94
95                         *object_ptr = NULL;
96                 }
97
98                 return NULL;
99         }
100
101         for (name = first_object; name; name = va_arg (args, const gchar *)) {
102                 object_ptr = va_arg (args, GObject**);
103
104                 *object_ptr = gtk_builder_get_object (gui, name);
105
106                 if (!*object_ptr) {
107                         g_warning ("File is missing object '%s'.", name);
108                         continue;
109                 }
110         }
111
112         return gui;
113 }
114
115 GtkBuilder *
116 empathy_builder_get_file (const gchar *filename,
117                           const gchar *first_object,
118                           ...)
119 {
120         GtkBuilder *gui;
121         va_list     args;
122
123         va_start (args, first_object);
124         gui = builder_get_file_valist (filename, first_object, args);
125         va_end (args);
126
127         return gui;
128 }
129
130 void
131 empathy_builder_connect (GtkBuilder *gui,
132                          gpointer    user_data,
133                          gchar      *first_object,
134                          ...)
135 {
136         va_list      args;
137         const gchar *name;
138         const gchar *sig;
139         GObject     *object;
140         GCallback    callback;
141
142         va_start (args, first_object);
143         for (name = first_object; name; name = va_arg (args, const gchar *)) {
144                 sig = va_arg (args, const gchar *);
145                 callback = va_arg (args, GCallback);
146
147                 object = gtk_builder_get_object (gui, name);
148                 if (!object) {
149                         g_warning ("File is missing object '%s'.", name);
150                         continue;
151                 }
152
153                 g_signal_connect (object, sig, callback, user_data);
154         }
155
156         va_end (args);
157 }
158
159 GtkWidget *
160 empathy_builder_unref_and_keep_widget (GtkBuilder *gui,
161                                        GtkWidget  *widget)
162 {
163         /* On construction gui sinks the initial reference to widget. When gui
164          * is finalized it will drop its ref to widget. We take our own ref to
165          * prevent widget being finalised. The widget is forced to have a
166          * floating reference, like when it was initially unowned so that it can
167          * be used like any other GtkWidget. */
168
169         g_object_ref (widget);
170         g_object_force_floating (G_OBJECT (widget));
171         g_object_unref (gui);
172
173         return widget;
174 }
175
176 const gchar *
177 empathy_icon_name_for_presence (TpConnectionPresenceType presence)
178 {
179         switch (presence) {
180         case TP_CONNECTION_PRESENCE_TYPE_AVAILABLE:
181                 return EMPATHY_IMAGE_AVAILABLE;
182         case TP_CONNECTION_PRESENCE_TYPE_BUSY:
183                 return EMPATHY_IMAGE_BUSY;
184         case TP_CONNECTION_PRESENCE_TYPE_AWAY:
185                 return EMPATHY_IMAGE_AWAY;
186         case TP_CONNECTION_PRESENCE_TYPE_EXTENDED_AWAY:
187                 if (gtk_icon_theme_has_icon (gtk_icon_theme_get_default (),
188                                              EMPATHY_IMAGE_EXT_AWAY))
189                         return EMPATHY_IMAGE_EXT_AWAY;
190
191                 /* The 'extended-away' icon is not an official one so we fallback to idle if
192                  * it's not implemented */
193                 return EMPATHY_IMAGE_IDLE;
194         case TP_CONNECTION_PRESENCE_TYPE_HIDDEN:
195                 if (gtk_icon_theme_has_icon (gtk_icon_theme_get_default (),
196                                              EMPATHY_IMAGE_HIDDEN))
197                         return EMPATHY_IMAGE_HIDDEN;
198
199                 /* The 'hidden' icon is not an official one so we fallback to offline if
200                  * it's not implemented */
201                 return EMPATHY_IMAGE_OFFLINE;
202         case TP_CONNECTION_PRESENCE_TYPE_OFFLINE:
203         case TP_CONNECTION_PRESENCE_TYPE_ERROR:
204                 return EMPATHY_IMAGE_OFFLINE;
205         case TP_CONNECTION_PRESENCE_TYPE_UNKNOWN:
206                 return EMPATHY_IMAGE_PENDING;
207         case TP_CONNECTION_PRESENCE_TYPE_UNSET:
208                 return NULL;
209         }
210
211         return NULL;
212 }
213
214 const gchar *
215 empathy_icon_name_for_contact (EmpathyContact *contact)
216 {
217         TpConnectionPresenceType presence;
218
219         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact),
220                               EMPATHY_IMAGE_OFFLINE);
221
222         presence = empathy_contact_get_presence (contact);
223         return empathy_icon_name_for_presence (presence);
224 }
225
226 const gchar *
227 empathy_icon_name_for_individual (FolksIndividual *individual)
228 {
229         FolksPresenceType folks_presence;
230         TpConnectionPresenceType presence;
231
232         folks_presence = folks_individual_get_presence_type (individual);
233         presence = empathy_folks_presence_type_to_tp (folks_presence);
234
235         return empathy_icon_name_for_presence (presence);
236 }
237
238 const gchar *
239 empathy_protocol_name_for_contact (EmpathyContact   *contact)
240 {
241         TpAccount     *account;
242
243         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
244
245         account = empathy_contact_get_account (contact);
246         if (account == NULL) {
247                 return NULL;
248         }
249
250         return tp_account_get_icon_name (account);
251 }
252
253 GdkPixbuf *
254 empathy_pixbuf_from_data (gchar *data,
255                           gsize  data_size)
256 {
257         return empathy_pixbuf_from_data_and_mime (data, data_size, NULL);
258 }
259
260 GdkPixbuf *
261 empathy_pixbuf_from_data_and_mime (gchar  *data,
262                                    gsize   data_size,
263                                    gchar **mime_type)
264 {
265         GdkPixbufLoader *loader;
266         GdkPixbufFormat *format;
267         GdkPixbuf       *pixbuf = NULL;
268         gchar          **mime_types;
269         GError          *error = NULL;
270
271         if (!data) {
272                 return NULL;
273         }
274
275         loader = gdk_pixbuf_loader_new ();
276         if (!gdk_pixbuf_loader_write (loader, (guchar *) data, data_size, &error)) {
277                 DEBUG ("Failed to write to pixbuf loader: %s",
278                         error ? error->message : "No error given");
279                 goto out;
280         }
281         if (!gdk_pixbuf_loader_close (loader, &error)) {
282                 DEBUG ("Failed to close pixbuf loader: %s",
283                         error ? error->message : "No error given");
284                 goto out;
285         }
286
287         pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
288         if (pixbuf) {
289                 g_object_ref (pixbuf);
290
291                 if (mime_type != NULL) {
292                         format = gdk_pixbuf_loader_get_format (loader);
293                         mime_types = gdk_pixbuf_format_get_mime_types (format);
294
295                         *mime_type = g_strdup (*mime_types);
296                         if (mime_types[1] != NULL) {
297                                 DEBUG ("Loader supports more than one mime "
298                                         "type! Picking the first one, %s",
299                                         *mime_type);
300                         }
301                         g_strfreev (mime_types);
302                 }
303         }
304
305 out:
306         g_clear_error (&error);
307         g_object_unref (loader);
308
309         return pixbuf;
310 }
311
312 struct SizeData {
313         gint     width;
314         gint     height;
315         gboolean preserve_aspect_ratio;
316 };
317
318 static void
319 pixbuf_from_avatar_size_prepared_cb (GdkPixbufLoader *loader,
320                                      int              width,
321                                      int              height,
322                                      struct SizeData *data)
323 {
324         g_return_if_fail (width > 0 && height > 0);
325
326         if (data->preserve_aspect_ratio && (data->width > 0 || data->height > 0)) {
327                 if (width < data->width && height < data->height) {
328                         width = width;
329                         height = height;
330                 }
331
332                 if (data->width < 0) {
333                         width = width * (double) data->height / (gdouble) height;
334                         height = data->height;
335                 } else if (data->height < 0) {
336                         height = height * (double) data->width / (double) width;
337                         width = data->width;
338                 } else if ((double) height * (double) data->width >
339                            (double) width * (double) data->height) {
340                         width = 0.5 + (double) width * (double) data->height / (double) height;
341                         height = data->height;
342                 } else {
343                         height = 0.5 + (double) height * (double) data->width / (double) width;
344                         width = data->width;
345                 }
346         } else {
347                 if (data->width > 0) {
348                         width = data->width;
349                 }
350
351                 if (data->height > 0) {
352                         height = data->height;
353                 }
354         }
355
356         gdk_pixbuf_loader_set_size (loader, width, height);
357 }
358
359 static void
360 empathy_avatar_pixbuf_roundify (GdkPixbuf *pixbuf)
361 {
362         gint width, height, rowstride;
363         guchar *pixels;
364
365         width = gdk_pixbuf_get_width (pixbuf);
366         height = gdk_pixbuf_get_height (pixbuf);
367         rowstride = gdk_pixbuf_get_rowstride (pixbuf);
368         pixels = gdk_pixbuf_get_pixels (pixbuf);
369
370         if (width < 6 || height < 6) {
371                 return;
372         }
373
374         /* Top left */
375         pixels[3] = 0;
376         pixels[7] = 0x80;
377         pixels[11] = 0xC0;
378         pixels[rowstride + 3] = 0x80;
379         pixels[rowstride * 2 + 3] = 0xC0;
380
381         /* Top right */
382         pixels[width * 4 - 1] = 0;
383         pixels[width * 4 - 5] = 0x80;
384         pixels[width * 4 - 9] = 0xC0;
385         pixels[rowstride + (width * 4) - 1] = 0x80;
386         pixels[(2 * rowstride) + (width * 4) - 1] = 0xC0;
387
388         /* Bottom left */
389         pixels[(height - 1) * rowstride + 3] = 0;
390         pixels[(height - 1) * rowstride + 7] = 0x80;
391         pixels[(height - 1) * rowstride + 11] = 0xC0;
392         pixels[(height - 2) * rowstride + 3] = 0x80;
393         pixels[(height - 3) * rowstride + 3] = 0xC0;
394
395         /* Bottom right */
396         pixels[height * rowstride - 1] = 0;
397         pixels[(height - 1) * rowstride - 1] = 0x80;
398         pixels[(height - 2) * rowstride - 1] = 0xC0;
399         pixels[height * rowstride - 5] = 0x80;
400         pixels[height * rowstride - 9] = 0xC0;
401 }
402
403 static gboolean
404 empathy_gdk_pixbuf_is_opaque (GdkPixbuf *pixbuf)
405 {
406         gint width, height, rowstride, i;
407         guchar *pixels;
408         guchar *row;
409
410         width = gdk_pixbuf_get_width (pixbuf);
411         height = gdk_pixbuf_get_height (pixbuf);
412         rowstride = gdk_pixbuf_get_rowstride (pixbuf);
413         pixels = gdk_pixbuf_get_pixels (pixbuf);
414
415         row = pixels;
416         for (i = 3; i < rowstride; i+=4) {
417                 if (row[i] < 0xfe) {
418                         return FALSE;
419                 }
420         }
421
422         for (i = 1; i < height - 1; i++) {
423                 row = pixels + (i*rowstride);
424                 if (row[3] < 0xfe || row[rowstride-1] < 0xfe) {
425                         return FALSE;
426                 }
427         }
428
429         row = pixels + ((height-1) * rowstride);
430         for (i = 3; i < rowstride; i+=4) {
431                 if (row[i] < 0xfe) {
432                         return FALSE;
433                 }
434         }
435
436         return TRUE;
437 }
438
439 static GdkPixbuf *
440 avatar_pixbuf_from_loader (GdkPixbufLoader *loader)
441 {
442         GdkPixbuf *pixbuf;
443
444         pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
445         if (!gdk_pixbuf_get_has_alpha (pixbuf)) {
446                 GdkPixbuf *rounded_pixbuf;
447
448                 rounded_pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8,
449                                                  gdk_pixbuf_get_width (pixbuf),
450                                                  gdk_pixbuf_get_height (pixbuf));
451                 gdk_pixbuf_copy_area (pixbuf, 0, 0,
452                                       gdk_pixbuf_get_width (pixbuf),
453                                       gdk_pixbuf_get_height (pixbuf),
454                                       rounded_pixbuf,
455                                       0, 0);
456                 pixbuf = rounded_pixbuf;
457         } else {
458                 g_object_ref (pixbuf);
459         }
460
461         if (empathy_gdk_pixbuf_is_opaque (pixbuf)) {
462                 empathy_avatar_pixbuf_roundify (pixbuf);
463         }
464
465         return pixbuf;
466 }
467
468 GdkPixbuf *
469 empathy_pixbuf_from_avatar_scaled (EmpathyAvatar *avatar,
470                                   gint          width,
471                                   gint          height)
472 {
473         GdkPixbuf        *pixbuf;
474         GdkPixbufLoader  *loader;
475         struct SizeData   data;
476         GError           *error = NULL;
477
478         if (!avatar) {
479                 return NULL;
480         }
481
482         data.width = width;
483         data.height = height;
484         data.preserve_aspect_ratio = TRUE;
485
486         loader = gdk_pixbuf_loader_new ();
487
488         g_signal_connect (loader, "size-prepared",
489                           G_CALLBACK (pixbuf_from_avatar_size_prepared_cb),
490                           &data);
491
492         if (!gdk_pixbuf_loader_write (loader, avatar->data, avatar->len, &error)) {
493                 g_warning ("Couldn't write avatar image:%p with "
494                            "length:%" G_GSIZE_FORMAT " to pixbuf loader: %s",
495                            avatar->data, avatar->len, error->message);
496                 g_error_free (error);
497                 return NULL;
498         }
499
500         gdk_pixbuf_loader_close (loader, NULL);
501         pixbuf = avatar_pixbuf_from_loader (loader);
502
503         g_object_unref (loader);
504
505         return pixbuf;
506 }
507
508 GdkPixbuf *
509 empathy_pixbuf_avatar_from_contact_scaled (EmpathyContact *contact,
510                                           gint           width,
511                                           gint           height)
512 {
513         EmpathyAvatar *avatar;
514
515         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
516
517         avatar = empathy_contact_get_avatar (contact);
518
519         return empathy_pixbuf_from_avatar_scaled (avatar, width, height);
520 }
521
522 typedef struct {
523         FolksIndividual *individual;
524         EmpathyPixbufAvatarFromIndividualCb callback;
525         gpointer user_data;
526         guint width;
527         guint height;
528 } PixbufAvatarFromIndividualClosure;
529
530 static PixbufAvatarFromIndividualClosure *
531 pixbuf_avatar_from_individual_closure_new (FolksIndividual                     *individual,
532                                            gint                                 width,
533                                            gint                                 height,
534                                            EmpathyPixbufAvatarFromIndividualCb  callback,
535                                            gpointer                             user_data)
536 {
537         PixbufAvatarFromIndividualClosure *closure;
538
539         g_return_val_if_fail (FOLKS_IS_INDIVIDUAL (individual), NULL);
540
541         closure = g_new0 (PixbufAvatarFromIndividualClosure, 1);
542         closure->individual = g_object_ref (individual);
543         closure->callback = callback;
544         closure->user_data = user_data;
545         closure->width = width;
546         closure->height = height;
547
548         return closure;
549 }
550
551 static void
552 pixbuf_avatar_from_individual_closure_free (
553                 PixbufAvatarFromIndividualClosure *closure)
554 {
555         g_object_unref (closure->individual);
556         g_free (closure);
557 }
558
559 static void
560 avatar_file_load_contents_cb (GObject      *object,
561                               GAsyncResult *result,
562                               gpointer      user_data)
563 {
564         GFile *file = G_FILE (object);
565         PixbufAvatarFromIndividualClosure *closure = user_data;
566         char *data;
567         gsize data_size;
568         struct SizeData size_data;
569         GError *error = NULL;
570         GdkPixbufLoader *loader = NULL;
571         GdkPixbuf *pixbuf = NULL;
572
573         if (!g_file_load_contents_finish (file, result, &data, &data_size,
574                                 NULL, &error)) {
575                 DEBUG ("failed to load avatar from file: %s",
576                                 error->message);
577                 goto out;
578         }
579
580         size_data.width = closure->width;
581         size_data.height = closure->height;
582         size_data.preserve_aspect_ratio = TRUE;
583
584         loader = gdk_pixbuf_loader_new ();
585
586         /* XXX: this seems a bit racy, but apparently works well enough */
587         g_signal_connect (loader, "size-prepared",
588                           G_CALLBACK (pixbuf_from_avatar_size_prepared_cb),
589                           &size_data);
590
591         if (!gdk_pixbuf_loader_write (loader, (guchar *) data, data_size,
592                                 &error)) {
593                 DEBUG ("Failed to write to pixbuf loader: %s",
594                         error ? error->message : "No error given");
595                 goto out;
596         }
597         if (!gdk_pixbuf_loader_close (loader, &error)) {
598                 DEBUG ("Failed to close pixbuf loader: %s",
599                         error ? error->message : "No error given");
600                 goto out;
601         }
602
603         pixbuf = avatar_pixbuf_from_loader (loader);
604
605         closure->callback (closure->individual, pixbuf, closure->user_data);
606
607 out:
608         g_clear_error (&error);
609         g_free (data);
610         if (loader != NULL)
611                 g_object_unref (loader);
612         pixbuf_avatar_from_individual_closure_free (closure);
613 }
614
615 void
616 empathy_pixbuf_avatar_from_individual_scaled_async (FolksIndividual                     *individual,
617                                                     gint                                 width,
618                                                     gint                                 height,
619                                                     EmpathyPixbufAvatarFromIndividualCb  callback,
620                                                     gpointer                             user_data)
621 {
622         GFile *avatar_file;
623         PixbufAvatarFromIndividualClosure *closure;
624
625         avatar_file = folks_avatar_get_avatar (FOLKS_AVATAR (individual));
626         if (avatar_file == NULL) {
627                 goto out;
628         }
629
630         closure = pixbuf_avatar_from_individual_closure_new (individual, width,
631                                                              height, callback,
632                                                              user_data);
633         if (closure == NULL)
634                 goto out;
635
636         g_file_load_contents_async (avatar_file, NULL,
637                         avatar_file_load_contents_cb, closure);
638
639         return;
640
641 out:
642         callback (individual, NULL, user_data);
643 }
644
645 GdkPixbuf *
646 empathy_pixbuf_contact_status_icon (EmpathyContact *contact,
647                                    gboolean       show_protocol)
648 {
649         const gchar *icon_name;
650
651         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
652
653         icon_name = empathy_icon_name_for_contact (contact);
654
655         if (icon_name == NULL) {
656                 return NULL;
657         }
658         return empathy_pixbuf_contact_status_icon_with_icon_name (contact,
659             icon_name,
660             show_protocol);
661 }
662
663 GdkPixbuf *
664 empathy_pixbuf_contact_status_icon_with_icon_name (EmpathyContact *contact,
665                                           const gchar    *icon_name,
666                                           gboolean       show_protocol)
667 {
668         GdkPixbuf *pix_status;
669         GdkPixbuf *pix_protocol;
670         gchar     *icon_filename;
671         gint       height, width;
672         gint       numerator, denominator;
673
674         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact) ||
675                         (show_protocol == FALSE), NULL);
676         g_return_val_if_fail (icon_name != NULL, NULL);
677
678         numerator = 3;
679         denominator = 4;
680
681         icon_filename = empathy_filename_from_icon_name (icon_name,
682                                                          GTK_ICON_SIZE_MENU);
683         if (icon_filename == NULL) {
684                 DEBUG ("icon name: %s could not be found\n", icon_name);
685                 return NULL;
686         }
687
688         pix_status = gdk_pixbuf_new_from_file (icon_filename, NULL);
689
690         if (pix_status == NULL) {
691                 DEBUG ("Could not open icon %s\n", icon_filename);
692                 g_free (icon_filename);
693                 return NULL;
694         }
695
696         g_free (icon_filename);
697
698         if (!show_protocol)
699                 return pix_status;
700
701         height = gdk_pixbuf_get_height (pix_status);
702         width = gdk_pixbuf_get_width (pix_status);
703
704         pix_protocol = empathy_pixbuf_protocol_from_contact_scaled (contact,
705                                                                     width * numerator / denominator,
706                                                                     height * numerator / denominator);
707
708         if (pix_protocol == NULL) {
709                 return pix_status;
710         }
711         gdk_pixbuf_composite (pix_protocol, pix_status,
712             0, height - height * numerator / denominator,
713             width * numerator / denominator, height * numerator / denominator,
714             0, height - height * numerator / denominator,
715             1, 1,
716             GDK_INTERP_BILINEAR, 255);
717
718         g_object_unref (pix_protocol);
719
720         return pix_status;
721 }
722
723 GdkPixbuf *
724 empathy_pixbuf_protocol_from_contact_scaled (EmpathyContact *contact,
725                                           gint           width,
726                                           gint           height)
727 {
728         TpAccount *account;
729         gchar     *filename;
730         GdkPixbuf *pixbuf = NULL;
731
732         g_return_val_if_fail (EMPATHY_IS_CONTACT (contact), NULL);
733
734         account = empathy_contact_get_account (contact);
735         filename = empathy_filename_from_icon_name (tp_account_get_icon_name (account),
736                                                     GTK_ICON_SIZE_MENU);
737         if (filename != NULL) {
738                 pixbuf = gdk_pixbuf_new_from_file_at_size (filename, width, height, NULL);
739                 g_free (filename);
740         }
741
742         return pixbuf;
743 }
744
745 GdkPixbuf *
746 empathy_pixbuf_scale_down_if_necessary (GdkPixbuf *pixbuf, gint max_size)
747 {
748         gint      width, height;
749         gdouble   factor;
750
751         width = gdk_pixbuf_get_width (pixbuf);
752         height = gdk_pixbuf_get_height (pixbuf);
753
754         if (width > 0 && (width > max_size || height > max_size)) {
755                 factor = (gdouble) max_size / MAX (width, height);
756
757                 width = width * factor;
758                 height = height * factor;
759
760                 return gdk_pixbuf_scale_simple (pixbuf,
761                                                 width, height,
762                                                 GDK_INTERP_HYPER);
763         }
764
765         return g_object_ref (pixbuf);
766 }
767
768 GdkPixbuf *
769 empathy_pixbuf_from_icon_name_sized (const gchar *icon_name,
770                                      gint size)
771 {
772         GtkIconTheme *theme;
773         GdkPixbuf *pixbuf;
774         GError *error = NULL;
775
776         if (!icon_name) {
777                 return NULL;
778         }
779
780         theme = gtk_icon_theme_get_default ();
781
782         pixbuf = gtk_icon_theme_load_icon (theme,
783                                            icon_name,
784                                            size,
785                                            0,
786                                            &error);
787         if (error) {
788                 DEBUG ("Error loading icon: %s", error->message);
789                 g_clear_error (&error);
790         }
791
792         return pixbuf;
793 }
794
795 GdkPixbuf *
796 empathy_pixbuf_from_icon_name (const gchar *icon_name,
797                                GtkIconSize  icon_size)
798 {
799         gint  w, h;
800         gint  size = 48;
801
802         if (!icon_name) {
803                 return NULL;
804         }
805
806         if (gtk_icon_size_lookup (icon_size, &w, &h)) {
807                 size = (w + h) / 2;
808         }
809
810         return empathy_pixbuf_from_icon_name_sized (icon_name, size);
811 }
812
813 gchar *
814 empathy_filename_from_icon_name (const gchar *icon_name,
815                                  GtkIconSize  icon_size)
816 {
817         GtkIconTheme *icon_theme;
818         GtkIconInfo  *icon_info;
819         gint          w, h;
820         gint          size = 48;
821         gchar        *ret;
822
823         icon_theme = gtk_icon_theme_get_default ();
824
825         if (gtk_icon_size_lookup (icon_size, &w, &h)) {
826                 size = (w + h) / 2;
827         }
828
829         icon_info = gtk_icon_theme_lookup_icon (icon_theme, icon_name, size, 0);
830         ret = g_strdup (gtk_icon_info_get_filename (icon_info));
831         gtk_icon_info_free (icon_info);
832
833         return ret;
834 }
835
836 /* Stolen from GtkSourceView, hence the weird intendation. Please keep it like
837  * that to make it easier to apply changes from the original code.
838  */
839 #define GTK_TEXT_UNKNOWN_CHAR 0xFFFC
840
841 /* this function acts like g_utf8_offset_to_pointer() except that if it finds a
842  * decomposable character it consumes the decomposition length from the given
843  * offset.  So it's useful when the offset was calculated for the normalized
844  * version of str, but we need a pointer to str itself. */
845 static const gchar *
846 pointer_from_offset_skipping_decomp (const gchar *str, gint offset)
847 {
848         gchar *casefold, *normal;
849         const gchar *p, *q;
850
851         p = str;
852         while (offset > 0)
853         {
854                 q = g_utf8_next_char (p);
855                 casefold = g_utf8_casefold (p, q - p);
856                 normal = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
857                 offset -= g_utf8_strlen (normal, -1);
858                 g_free (casefold);
859                 g_free (normal);
860                 p = q;
861         }
862         return p;
863 }
864
865 static const gchar *
866 g_utf8_strcasestr (const gchar *haystack, const gchar *needle)
867 {
868         gsize needle_len;
869         gsize haystack_len;
870         const gchar *ret = NULL;
871         gchar *p;
872         gchar *casefold;
873         gchar *caseless_haystack;
874         gint i;
875
876         g_return_val_if_fail (haystack != NULL, NULL);
877         g_return_val_if_fail (needle != NULL, NULL);
878
879         casefold = g_utf8_casefold (haystack, -1);
880         caseless_haystack = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
881         g_free (casefold);
882
883         needle_len = g_utf8_strlen (needle, -1);
884         haystack_len = g_utf8_strlen (caseless_haystack, -1);
885
886         if (needle_len == 0)
887         {
888                 ret = (gchar *) haystack;
889                 goto finally_1;
890         }
891
892         if (haystack_len < needle_len)
893         {
894                 ret = NULL;
895                 goto finally_1;
896         }
897
898         p = (gchar *) caseless_haystack;
899         needle_len = strlen (needle);
900         i = 0;
901
902         while (*p)
903         {
904                 if ((strncmp (p, needle, needle_len) == 0))
905                 {
906                         ret = pointer_from_offset_skipping_decomp (haystack, i);
907                         goto finally_1;
908                 }
909
910                 p = g_utf8_next_char (p);
911                 i++;
912         }
913
914 finally_1:
915         g_free (caseless_haystack);
916
917         return ret;
918 }
919
920 static gboolean
921 g_utf8_caselessnmatch (const char *s1, const char *s2,
922                        gssize n1, gssize n2)
923 {
924         gchar *casefold;
925         gchar *normalized_s1;
926         gchar *normalized_s2;
927         gint len_s1;
928         gint len_s2;
929         gboolean ret = FALSE;
930
931         g_return_val_if_fail (s1 != NULL, FALSE);
932         g_return_val_if_fail (s2 != NULL, FALSE);
933         g_return_val_if_fail (n1 > 0, FALSE);
934         g_return_val_if_fail (n2 > 0, FALSE);
935
936         casefold = g_utf8_casefold (s1, n1);
937         normalized_s1 = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
938         g_free (casefold);
939
940         casefold = g_utf8_casefold (s2, n2);
941         normalized_s2 = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
942         g_free (casefold);
943
944         len_s1 = strlen (normalized_s1);
945         len_s2 = strlen (normalized_s2);
946
947         if (len_s1 < len_s2)
948                 goto finally_2;
949
950         ret = (strncmp (normalized_s1, normalized_s2, len_s2) == 0);
951
952 finally_2:
953         g_free (normalized_s1);
954         g_free (normalized_s2);
955
956         return ret;
957 }
958
959 static void
960 forward_chars_with_skipping (GtkTextIter *iter,
961                              gint         count,
962                              gboolean     skip_invisible,
963                              gboolean     skip_nontext,
964                              gboolean     skip_decomp)
965 {
966         gint i;
967
968         g_return_if_fail (count >= 0);
969
970         i = count;
971
972         while (i > 0)
973         {
974                 gboolean ignored = FALSE;
975
976                 /* minimal workaround to avoid the infinite loop of bug #168247.
977                  * It doesn't fix the problemjust the symptom...
978                  */
979                 if (gtk_text_iter_is_end (iter))
980                         return;
981
982                 if (skip_nontext && gtk_text_iter_get_char (iter) == GTK_TEXT_UNKNOWN_CHAR)
983                         ignored = TRUE;
984
985                 if (!ignored && skip_invisible &&
986                     /* _gtk_text_btree_char_is_invisible (iter)*/ FALSE)
987                         ignored = TRUE;
988
989                 if (!ignored && skip_decomp)
990                 {
991                         /* being UTF8 correct sucks; this accounts for extra
992                            offsets coming from canonical decompositions of
993                            UTF8 characters (e.g. accented characters) which
994                            g_utf8_normalize () performs */
995                         gchar *normal;
996                         gchar buffer[6];
997                         gint buffer_len;
998
999                         buffer_len = g_unichar_to_utf8 (gtk_text_iter_get_char (iter), buffer);
1000                         normal = g_utf8_normalize (buffer, buffer_len, G_NORMALIZE_NFD);
1001                         i -= (g_utf8_strlen (normal, -1) - 1);
1002                         g_free (normal);
1003                 }
1004
1005                 gtk_text_iter_forward_char (iter);
1006
1007                 if (!ignored)
1008                         --i;
1009         }
1010 }
1011
1012 static gboolean
1013 lines_match (const GtkTextIter *start,
1014              const gchar      **lines,
1015              gboolean           visible_only,
1016              gboolean           slice,
1017              GtkTextIter       *match_start,
1018              GtkTextIter       *match_end)
1019 {
1020         GtkTextIter next;
1021         gchar *line_text;
1022         const gchar *found;
1023         gint offset;
1024
1025         if (*lines == NULL || **lines == '\0')
1026         {
1027                 if (match_start)
1028                         *match_start = *start;
1029                 if (match_end)
1030                         *match_end = *start;
1031                 return TRUE;
1032         }
1033
1034         next = *start;
1035         gtk_text_iter_forward_line (&next);
1036
1037         /* No more text in buffer, but *lines is nonempty */
1038         if (gtk_text_iter_equal (start, &next))
1039                 return FALSE;
1040
1041         if (slice)
1042         {
1043                 if (visible_only)
1044                         line_text = gtk_text_iter_get_visible_slice (start, &next);
1045                 else
1046                         line_text = gtk_text_iter_get_slice (start, &next);
1047         }
1048         else
1049         {
1050                 if (visible_only)
1051                         line_text = gtk_text_iter_get_visible_text (start, &next);
1052                 else
1053                         line_text = gtk_text_iter_get_text (start, &next);
1054         }
1055
1056         if (match_start) /* if this is the first line we're matching */
1057         {
1058                 found = g_utf8_strcasestr (line_text, *lines);
1059         }
1060         else
1061         {
1062                 /* If it's not the first line, we have to match from the
1063                  * start of the line.
1064                  */
1065                 if (g_utf8_caselessnmatch (line_text, *lines, strlen (line_text),
1066                                            strlen (*lines)))
1067                         found = line_text;
1068                 else
1069                         found = NULL;
1070         }
1071
1072         if (found == NULL)
1073         {
1074                 g_free (line_text);
1075                 return FALSE;
1076         }
1077
1078         /* Get offset to start of search string */
1079         offset = g_utf8_strlen (line_text, found - line_text);
1080
1081         next = *start;
1082
1083         /* If match start needs to be returned, set it to the
1084          * start of the search string.
1085          */
1086         forward_chars_with_skipping (&next, offset, visible_only, !slice, FALSE);
1087         if (match_start)
1088         {
1089                 *match_start = next;
1090         }
1091
1092         /* Go to end of search string */
1093         forward_chars_with_skipping (&next, g_utf8_strlen (*lines, -1), visible_only, !slice, TRUE);
1094
1095         g_free (line_text);
1096
1097         ++lines;
1098
1099         if (match_end)
1100                 *match_end = next;
1101
1102         /* pass NULL for match_start, since we don't need to find the
1103          * start again.
1104          */
1105         return lines_match (&next, lines, visible_only, slice, NULL, match_end);
1106 }
1107
1108 /* strsplit () that retains the delimiter as part of the string. */
1109 static gchar **
1110 strbreakup (const char *string,
1111             const char *delimiter,
1112             gint        max_tokens)
1113 {
1114         GSList *string_list = NULL, *slist;
1115         gchar **str_array, *s, *casefold, *new_string;
1116         guint i, n = 1;
1117
1118         g_return_val_if_fail (string != NULL, NULL);
1119         g_return_val_if_fail (delimiter != NULL, NULL);
1120
1121         if (max_tokens < 1)
1122                 max_tokens = G_MAXINT;
1123
1124         s = strstr (string, delimiter);
1125         if (s)
1126         {
1127                 guint delimiter_len = strlen (delimiter);
1128
1129                 do
1130                 {
1131                         guint len;
1132
1133                         len = s - string + delimiter_len;
1134                         new_string = g_new (gchar, len + 1);
1135                         strncpy (new_string, string, len);
1136                         new_string[len] = 0;
1137                         casefold = g_utf8_casefold (new_string, -1);
1138                         g_free (new_string);
1139                         new_string = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1140                         g_free (casefold);
1141                         string_list = g_slist_prepend (string_list, new_string);
1142                         n++;
1143                         string = s + delimiter_len;
1144                         s = strstr (string, delimiter);
1145                 } while (--max_tokens && s);
1146         }
1147
1148         if (*string)
1149         {
1150                 n++;
1151                 casefold = g_utf8_casefold (string, -1);
1152                 new_string = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1153                 g_free (casefold);
1154                 string_list = g_slist_prepend (string_list, new_string);
1155         }
1156
1157         str_array = g_new (gchar*, n);
1158
1159         i = n - 1;
1160
1161         str_array[i--] = NULL;
1162         for (slist = string_list; slist; slist = slist->next)
1163                 str_array[i--] = slist->data;
1164
1165         g_slist_free (string_list);
1166
1167         return str_array;
1168 }
1169
1170 gboolean
1171 empathy_text_iter_forward_search (const GtkTextIter   *iter,
1172                                  const gchar         *str,
1173                                  GtkTextIter         *match_start,
1174                                  GtkTextIter         *match_end,
1175                                  const GtkTextIter   *limit)
1176 {
1177         gchar **lines = NULL;
1178         GtkTextIter match;
1179         gboolean retval = FALSE;
1180         GtkTextIter search;
1181         gboolean visible_only;
1182         gboolean slice;
1183
1184         g_return_val_if_fail (iter != NULL, FALSE);
1185         g_return_val_if_fail (str != NULL, FALSE);
1186
1187         if (limit && gtk_text_iter_compare (iter, limit) >= 0)
1188                 return FALSE;
1189
1190         if (*str == '\0') {
1191                 /* If we can move one char, return the empty string there */
1192                 match = *iter;
1193
1194                 if (gtk_text_iter_forward_char (&match)) {
1195                         if (limit && gtk_text_iter_equal (&match, limit)) {
1196                                 return FALSE;
1197                         }
1198
1199                         if (match_start) {
1200                                 *match_start = match;
1201                         }
1202                         if (match_end) {
1203                                 *match_end = match;
1204                         }
1205                         return TRUE;
1206                 } else {
1207                         return FALSE;
1208                 }
1209         }
1210
1211         visible_only = TRUE;
1212         slice = FALSE;
1213
1214         /* locate all lines */
1215         lines = strbreakup (str, "\n", -1);
1216
1217         search = *iter;
1218
1219         do {
1220                 /* This loop has an inefficient worst-case, where
1221                  * gtk_text_iter_get_text () is called repeatedly on
1222                  * a single line.
1223                  */
1224                 GtkTextIter end;
1225
1226                 if (limit && gtk_text_iter_compare (&search, limit) >= 0) {
1227                         break;
1228                 }
1229
1230                 if (lines_match (&search, (const gchar**)lines,
1231                                  visible_only, slice, &match, &end)) {
1232                         if (limit == NULL ||
1233                             (limit && gtk_text_iter_compare (&end, limit) <= 0)) {
1234                                 retval = TRUE;
1235
1236                                 if (match_start) {
1237                                         *match_start = match;
1238                                 }
1239                                 if (match_end) {
1240                                         *match_end = end;
1241                                 }
1242                         }
1243                         break;
1244                 }
1245         } while (gtk_text_iter_forward_line (&search));
1246
1247         g_strfreev ((gchar **) lines);
1248
1249         return retval;
1250 }
1251
1252 static const gchar *
1253 g_utf8_strrcasestr (const gchar *haystack, const gchar *needle)
1254 {
1255         gsize needle_len;
1256         gsize haystack_len;
1257         const gchar *ret = NULL;
1258         gchar *p;
1259         gchar *casefold;
1260         gchar *caseless_haystack;
1261         gint i;
1262
1263         g_return_val_if_fail (haystack != NULL, NULL);
1264         g_return_val_if_fail (needle != NULL, NULL);
1265
1266         casefold = g_utf8_casefold (haystack, -1);
1267         caseless_haystack = g_utf8_normalize (casefold, -1, G_NORMALIZE_NFD);
1268         g_free (casefold);
1269
1270         needle_len = g_utf8_strlen (needle, -1);
1271         haystack_len = g_utf8_strlen (caseless_haystack, -1);
1272
1273         if (needle_len == 0)
1274         {
1275                 ret = (gchar *) haystack;
1276                 goto finally_1;
1277         }
1278
1279         if (haystack_len < needle_len)
1280         {
1281                 ret = NULL;
1282                 goto finally_1;
1283         }
1284
1285         i = haystack_len - needle_len;
1286         p = g_utf8_offset_to_pointer (caseless_haystack, i);
1287         needle_len = strlen (needle);
1288
1289         while (p >= caseless_haystack)
1290         {
1291                 if (strncmp (p, needle, needle_len) == 0)
1292                 {
1293                         ret = pointer_from_offset_skipping_decomp (haystack, i);
1294                         goto finally_1;
1295                 }
1296
1297                 p = g_utf8_prev_char (p);
1298                 i--;
1299         }
1300
1301 finally_1:
1302         g_free (caseless_haystack);
1303
1304         return ret;
1305 }
1306
1307 static gboolean
1308 backward_lines_match (const GtkTextIter *start,
1309                       const gchar      **lines,
1310                       gboolean           visible_only,
1311                       gboolean           slice,
1312                       GtkTextIter       *match_start,
1313                       GtkTextIter       *match_end)
1314 {
1315         GtkTextIter line, next;
1316         gchar *line_text;
1317         const gchar *found;
1318         gint offset;
1319
1320         if (*lines == NULL || **lines == '\0')
1321         {
1322                 if (match_start)
1323                         *match_start = *start;
1324                 if (match_end)
1325                         *match_end = *start;
1326                 return TRUE;
1327         }
1328
1329         line = next = *start;
1330         if (gtk_text_iter_get_line_offset (&next) == 0)
1331         {
1332                 if (!gtk_text_iter_backward_line (&next))
1333                         return FALSE;
1334         }
1335         else
1336                 gtk_text_iter_set_line_offset (&next, 0);
1337
1338         if (slice)
1339         {
1340                 if (visible_only)
1341                         line_text = gtk_text_iter_get_visible_slice (&next, &line);
1342                 else
1343                         line_text = gtk_text_iter_get_slice (&next, &line);
1344         }
1345         else
1346         {
1347                 if (visible_only)
1348                         line_text = gtk_text_iter_get_visible_text (&next, &line);
1349                 else
1350                         line_text = gtk_text_iter_get_text (&next, &line);
1351         }
1352
1353         if (match_start) /* if this is the first line we're matching */
1354         {
1355                 found = g_utf8_strrcasestr (line_text, *lines);
1356         }
1357         else
1358         {
1359                 /* If it's not the first line, we have to match from the
1360                  * start of the line.
1361                  */
1362                 if (g_utf8_caselessnmatch (line_text, *lines, strlen (line_text),
1363                                            strlen (*lines)))
1364                         found = line_text;
1365                 else
1366                         found = NULL;
1367         }
1368
1369         if (found == NULL)
1370         {
1371                 g_free (line_text);
1372                 return FALSE;
1373         }
1374
1375         /* Get offset to start of search string */
1376         offset = g_utf8_strlen (line_text, found - line_text);
1377
1378         forward_chars_with_skipping (&next, offset, visible_only, !slice, FALSE);
1379
1380         /* If match start needs to be returned, set it to the
1381          * start of the search string.
1382          */
1383         if (match_start)
1384         {
1385                 *match_start = next;
1386         }
1387
1388         /* Go to end of search string */
1389         forward_chars_with_skipping (&next, g_utf8_strlen (*lines, -1), visible_only, !slice, TRUE);
1390
1391         g_free (line_text);
1392
1393         ++lines;
1394
1395         if (match_end)
1396                 *match_end = next;
1397
1398         /* try to match the rest of the lines forward, passing NULL
1399          * for match_start so lines_match will try to match the entire
1400          * line */
1401         return lines_match (&next, lines, visible_only,
1402                             slice, NULL, match_end);
1403 }
1404
1405 gboolean
1406 empathy_text_iter_backward_search (const GtkTextIter   *iter,
1407                                   const gchar         *str,
1408                                   GtkTextIter         *match_start,
1409                                   GtkTextIter         *match_end,
1410                                   const GtkTextIter   *limit)
1411 {
1412         gchar **lines = NULL;
1413         GtkTextIter match;
1414         gboolean retval = FALSE;
1415         GtkTextIter search;
1416         gboolean visible_only;
1417         gboolean slice;
1418
1419         g_return_val_if_fail (iter != NULL, FALSE);
1420         g_return_val_if_fail (str != NULL, FALSE);
1421
1422         if (limit && gtk_text_iter_compare (iter, limit) <= 0)
1423                 return FALSE;
1424
1425         if (*str == '\0')
1426         {
1427                 /* If we can move one char, return the empty string there */
1428                 match = *iter;
1429
1430                 if (gtk_text_iter_backward_char (&match))
1431                 {
1432                         if (limit && gtk_text_iter_equal (&match, limit))
1433                                 return FALSE;
1434
1435                         if (match_start)
1436                                 *match_start = match;
1437                         if (match_end)
1438                                 *match_end = match;
1439                         return TRUE;
1440                 }
1441                 else
1442                 {
1443                         return FALSE;
1444                 }
1445         }
1446
1447         visible_only = TRUE;
1448         slice = TRUE;
1449
1450         /* locate all lines */
1451         lines = strbreakup (str, "\n", -1);
1452
1453         search = *iter;
1454
1455         while (TRUE)
1456         {
1457                 /* This loop has an inefficient worst-case, where
1458                  * gtk_text_iter_get_text () is called repeatedly on
1459                  * a single line.
1460                  */
1461                 GtkTextIter end;
1462
1463                 if (limit && gtk_text_iter_compare (&search, limit) <= 0)
1464                         break;
1465
1466                 if (backward_lines_match (&search, (const gchar**)lines,
1467                                           visible_only, slice, &match, &end))
1468                 {
1469                         if (limit == NULL || (limit &&
1470                                               gtk_text_iter_compare (&end, limit) > 0))
1471                         {
1472                                 retval = TRUE;
1473
1474                                 if (match_start)
1475                                         *match_start = match;
1476                                 if (match_end)
1477                                         *match_end = end;
1478                         }
1479                         break;
1480                 }
1481
1482                 if (gtk_text_iter_get_line_offset (&search) == 0)
1483                 {
1484                         if (!gtk_text_iter_backward_line (&search))
1485                                 break;
1486                 }
1487                 else
1488                 {
1489                         gtk_text_iter_set_line_offset (&search, 0);
1490                 }
1491         }
1492
1493         g_strfreev ((gchar **) lines);
1494
1495         return retval;
1496 }
1497
1498 gboolean
1499 empathy_window_get_is_visible (GtkWindow *window)
1500 {
1501         GdkWindowState  state;
1502         GdkWindow      *gdk_window;
1503
1504         g_return_val_if_fail (GTK_IS_WINDOW (window), FALSE);
1505
1506         gdk_window = gtk_widget_get_window (GTK_WIDGET (window));
1507         if (!gdk_window) {
1508                 return FALSE;
1509         }
1510
1511         state = gdk_window_get_state (gdk_window);
1512         if (state & (GDK_WINDOW_STATE_WITHDRAWN | GDK_WINDOW_STATE_ICONIFIED)) {
1513                 return FALSE;
1514         }
1515
1516         return TRUE;
1517 }
1518
1519 void
1520 empathy_window_iconify (GtkWindow *window, GtkStatusIcon *status_icon)
1521 {
1522         GdkRectangle  icon_location;
1523         gulong        data[4];
1524         Display      *dpy;
1525         GdkWindow    *gdk_window;
1526
1527         gtk_status_icon_get_geometry (status_icon, NULL, &icon_location, NULL);
1528         gdk_window = gtk_widget_get_window (GTK_WIDGET (window));
1529         dpy = gdk_x11_drawable_get_xdisplay (gdk_window);
1530
1531         data[0] = icon_location.x;
1532         data[1] = icon_location.y;
1533         data[2] = icon_location.width;
1534         data[3] = icon_location.height;
1535
1536         XChangeProperty (dpy,
1537                          GDK_WINDOW_XID (gdk_window),
1538                          gdk_x11_get_xatom_by_name_for_display (
1539                                 gdk_drawable_get_display (gdk_window),
1540                          "_NET_WM_ICON_GEOMETRY"),
1541                          XA_CARDINAL, 32, PropModeReplace,
1542                          (guchar *)&data, 4);
1543
1544         gtk_window_set_skip_taskbar_hint (window, TRUE);
1545         gtk_window_iconify (window);
1546 }
1547
1548 /* Takes care of moving the window to the current workspace. */
1549 void
1550 empathy_window_present_with_time (GtkWindow *window,
1551                         guint32 timestamp)
1552 {
1553         GdkWindow *gdk_window;
1554
1555         g_return_if_fail (GTK_IS_WINDOW (window));
1556
1557         /* Move the window to the current workspace before trying to show it.
1558          * This is the behaviour people expect when clicking on the statusbar icon. */
1559         gdk_window = gtk_widget_get_window (GTK_WIDGET (window));
1560         if (gdk_window) {
1561                 gint x, y;
1562                 gint w, h;
1563
1564                 /* Has no effect if the WM has viewports, like compiz */
1565                 gdk_x11_window_move_to_current_desktop (gdk_window);
1566
1567                 /* If window is still off-screen, hide it to force it to
1568                  * reposition on the current workspace. */
1569                 gtk_window_get_position (window, &x, &y);
1570                 gtk_window_get_size (window, &w, &h);
1571                 if (!EMPATHY_RECT_IS_ON_SCREEN (x, y, w, h))
1572                         gtk_widget_hide (GTK_WIDGET (window));
1573         }
1574
1575         gtk_window_present_with_time (window, timestamp);
1576         gtk_window_set_skip_taskbar_hint (window, FALSE);
1577         gtk_window_deiconify (window);
1578 }
1579
1580 void
1581 empathy_window_present (GtkWindow *window)
1582 {
1583   empathy_window_present_with_time (window, GDK_CURRENT_TIME);
1584 }
1585
1586 GtkWindow *
1587 empathy_get_toplevel_window (GtkWidget *widget)
1588 {
1589         GtkWidget *toplevel;
1590
1591         g_return_val_if_fail (GTK_IS_WIDGET (widget), NULL);
1592
1593         toplevel = gtk_widget_get_toplevel (widget);
1594         if (GTK_IS_WINDOW (toplevel) &&
1595             gtk_widget_is_toplevel (toplevel)) {
1596                 return GTK_WINDOW (toplevel);
1597         }
1598
1599         return NULL;
1600 }
1601
1602 /** empathy_make_absolute_url_len:
1603  * @url: an url
1604  * @len: a length
1605  *
1606  * Same as #empathy_make_absolute_url but for a limited string length
1607  */
1608 gchar *
1609 empathy_make_absolute_url_len (const gchar *url,
1610                                guint len)
1611 {
1612         g_return_val_if_fail (url != NULL, NULL);
1613
1614         if (g_str_has_prefix (url, "ghelp:") ||
1615             g_str_has_prefix (url, "mailto:") ||
1616             strstr (url, ":/")) {
1617                 return g_strndup (url, len);
1618         }
1619
1620         if (strstr (url, "@")) {
1621                 return g_strdup_printf ("mailto:%.*s", len, url);
1622         }
1623
1624         return g_strdup_printf ("http://%.*s", len, url);
1625 }
1626
1627 /** empathy_make_absolute_url:
1628  * @url: an url
1629  *
1630  * The URL opening code can't handle schemeless strings, so we try to be
1631  * smart and add http if there is no scheme or doesn't look like a mail
1632  * address. This should work in most cases, and let us click on strings
1633  * like "www.gnome.org".
1634  *
1635  * Returns: a newly allocated url with proper mailto: or http:// prefix, use
1636  * g_free when your are done with it
1637  */
1638 gchar *
1639 empathy_make_absolute_url (const gchar *url)
1640 {
1641         return empathy_make_absolute_url_len (url, strlen (url));
1642 }
1643
1644 void
1645 empathy_url_show (GtkWidget *parent,
1646                   const char *url)
1647 {
1648         gchar  *real_url;
1649         GError *error = NULL;
1650
1651         g_return_if_fail (parent == NULL || GTK_IS_WIDGET (parent));
1652         g_return_if_fail (url != NULL);
1653
1654         real_url = empathy_make_absolute_url (url);
1655
1656         gtk_show_uri (parent ? gtk_widget_get_screen (parent) : NULL, real_url,
1657                       gtk_get_current_event_time (), &error);
1658
1659         if (error) {
1660                 GtkWidget *dialog;
1661
1662                 dialog = gtk_message_dialog_new (NULL, 0,
1663                                                  GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,
1664                                                  _("Unable to open URI"));
1665                 gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
1666                                                           "%s", error->message);
1667
1668                 g_signal_connect (dialog, "response",
1669                                   G_CALLBACK (gtk_widget_destroy),
1670                                   NULL);
1671                 gtk_window_present (GTK_WINDOW (dialog));
1672
1673                 g_clear_error (&error);
1674         }
1675
1676         g_free (real_url);
1677 }
1678
1679 void
1680 empathy_send_file (EmpathyContact *contact, GFile *file)
1681 {
1682         EmpathyFTFactory *factory;
1683         GtkRecentManager *manager;
1684         gchar *uri;
1685
1686         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1687         g_return_if_fail (G_IS_FILE (file));
1688
1689         factory = empathy_ft_factory_dup_singleton ();
1690
1691         empathy_ft_factory_new_transfer_outgoing (factory, contact, file);
1692
1693         uri = g_file_get_uri (file);
1694         manager = gtk_recent_manager_get_default ();
1695         gtk_recent_manager_add_item (manager, uri);
1696         g_free (uri);
1697
1698         g_object_unref (factory);
1699 }
1700
1701 void
1702 empathy_send_file_from_uri_list (EmpathyContact *contact, const gchar *uri_list)
1703 {
1704         const gchar *nl;
1705         GFile *file;
1706
1707         /* Only handle a single file for now.  It would be wicked cool to be
1708            able to do multiple files, offering to zip them or whatever like
1709            nautilus-sendto does.  Note that text/uri-list is defined to have
1710            each line terminated by \r\n, but we can be tolerant of applications
1711            that only use \n or don't terminate single-line entries.
1712         */
1713         nl = strstr (uri_list, "\r\n");
1714         if (!nl) {
1715                 nl = strchr (uri_list, '\n');
1716         }
1717         if (nl) {
1718                 gchar *uri = g_strndup (uri_list, nl - uri_list);
1719                 file = g_file_new_for_uri (uri);
1720                 g_free (uri);
1721         }
1722         else {
1723                 file = g_file_new_for_uri (uri_list);
1724         }
1725
1726         empathy_send_file (contact, file);
1727
1728         g_object_unref (file);
1729 }
1730
1731 static void
1732 file_manager_send_file_response_cb (GtkDialog      *widget,
1733                                     gint            response_id,
1734                                     EmpathyContact *contact)
1735 {
1736         GFile *file;
1737
1738         if (response_id == GTK_RESPONSE_OK) {
1739                 file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (widget));
1740
1741                 empathy_send_file (contact, file);
1742
1743                 g_object_unref (file);
1744         }
1745
1746         gtk_widget_destroy (GTK_WIDGET (widget));
1747 }
1748
1749 void
1750 empathy_send_file_with_file_chooser (EmpathyContact *contact)
1751 {
1752         GtkWidget               *widget;
1753         GtkWidget               *button;
1754
1755         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1756
1757         DEBUG ("Creating selection file chooser");
1758
1759         widget = gtk_file_chooser_dialog_new (_("Select a file"),
1760                                               NULL,
1761                                               GTK_FILE_CHOOSER_ACTION_OPEN,
1762                                               GTK_STOCK_CANCEL,
1763                                               GTK_RESPONSE_CANCEL,
1764                                               NULL);
1765
1766         /* send button */
1767         button = gtk_button_new_with_mnemonic (_("_Send"));
1768         gtk_button_set_image (GTK_BUTTON (button),
1769                 gtk_image_new_from_icon_name (EMPATHY_IMAGE_DOCUMENT_SEND,
1770                                               GTK_ICON_SIZE_BUTTON));
1771         gtk_widget_show (button);
1772         gtk_dialog_add_action_widget (GTK_DIALOG (widget), button,
1773                                       GTK_RESPONSE_OK);
1774         gtk_widget_set_can_default (button, TRUE);
1775         gtk_dialog_set_default_response (GTK_DIALOG (widget),
1776                                          GTK_RESPONSE_OK);
1777
1778         gtk_file_chooser_set_local_only (GTK_FILE_CHOOSER (widget), FALSE);
1779
1780         gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (widget),
1781                 g_get_home_dir ());
1782
1783         g_signal_connect (widget, "response",
1784                           G_CALLBACK (file_manager_send_file_response_cb),
1785                           contact);
1786
1787         gtk_widget_show (widget);
1788 }
1789
1790 static void
1791 file_manager_receive_file_response_cb (GtkDialog *dialog,
1792                                        GtkResponseType response,
1793                                        EmpathyFTHandler *handler)
1794 {
1795         EmpathyFTFactory *factory;
1796         GFile *file;
1797
1798         if (response == GTK_RESPONSE_OK) {
1799                 factory = empathy_ft_factory_dup_singleton ();
1800                 file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (dialog));
1801
1802                 empathy_ft_factory_set_destination_for_incoming_handler
1803                         (factory, handler, file);
1804
1805                 g_object_unref (factory);
1806                 g_object_unref (file);
1807         } else {
1808                 /* unref the handler, as we dismissed the file chooser,
1809                  * and refused the transfer.
1810                  */
1811                 g_object_unref (handler);
1812         }
1813
1814         gtk_widget_destroy (GTK_WIDGET (dialog));
1815 }
1816
1817 void
1818 empathy_receive_file_with_file_chooser (EmpathyFTHandler *handler)
1819 {
1820         GtkWidget *widget;
1821         const gchar *dir;
1822         EmpathyContact *contact;
1823         gchar *title;
1824
1825         contact = empathy_ft_handler_get_contact (handler);
1826         g_assert (contact != NULL);
1827
1828         title = g_strdup_printf (_("Incoming file from %s"),
1829                 empathy_contact_get_name (contact));
1830
1831         widget = gtk_file_chooser_dialog_new (title,
1832                                               NULL,
1833                                               GTK_FILE_CHOOSER_ACTION_SAVE,
1834                                               GTK_STOCK_CANCEL,
1835                                               GTK_RESPONSE_CANCEL,
1836                                               GTK_STOCK_SAVE,
1837                                               GTK_RESPONSE_OK,
1838                                               NULL);
1839         gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (widget),
1840                 empathy_ft_handler_get_filename (handler));
1841         gtk_file_chooser_set_do_overwrite_confirmation
1842                 (GTK_FILE_CHOOSER (widget), TRUE);
1843
1844         dir = g_get_user_special_dir (G_USER_DIRECTORY_DOWNLOAD);
1845         if (dir == NULL)
1846                 /* Fallback to $HOME if $XDG_DOWNLOAD_DIR is not set */
1847                 dir = g_get_home_dir ();
1848
1849         gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (widget), dir);
1850
1851         g_signal_connect (widget, "response",
1852                 G_CALLBACK (file_manager_receive_file_response_cb), handler);
1853
1854         gtk_widget_show (widget);
1855         g_free (title);
1856 }