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