]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-avatar-chooser.c
Report error to the user when converting the avatar fails.
[empathy.git] / libempathy-gtk / empathy-avatar-chooser.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  * Copyright (C) 2006-2007 Imendio AB.
4  * Copyright (C) 2007-2008 Collabora Ltd.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of version 2 of the GNU General Public
8  * License as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Authors: Based on Novell's e-image-chooser.
21  *          Xavier Claessens <xclaesse@gmail.com>
22  */
23
24 #include "config.h"
25
26 #include <string.h>
27
28 #include <glib/gi18n.h>
29 #include <gtk/gtk.h>
30 #include <gio/gio.h>
31
32 #include <libempathy/empathy-utils.h>
33 #include <libempathy/empathy-contact-factory.h>
34
35 #include "empathy-avatar-chooser.h"
36 #include "empathy-conf.h"
37 #include "empathy-ui-utils.h"
38
39 #define DEBUG_FLAG EMPATHY_DEBUG_OTHER
40 #include <libempathy/empathy-debug.h>
41
42 #define AVATAR_SIZE_SAVE 96
43 #define AVATAR_SIZE_VIEW 64
44 #define DEFAULT_DIR DATADIR"/pixmaps/faces"
45
46 #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyAvatarChooser)
47 typedef struct {
48         EmpathyContactFactory   *contact_factory;
49         McAccount               *account;
50         EmpathyTpContactFactory *tp_contact_factory;
51
52         gulong ready_handler_id;
53
54         EmpathyAvatar *avatar;
55 } EmpathyAvatarChooserPriv;
56
57 static void       avatar_chooser_finalize              (GObject              *object);
58 static void       avatar_chooser_set_account           (EmpathyAvatarChooser *self,
59                                                         McAccount            *account);
60 static void       avatar_chooser_set_image             (EmpathyAvatarChooser *chooser,
61                                                         EmpathyAvatar        *avatar,
62                                                         GdkPixbuf            *pixbuf,
63                                                         gboolean              set_locally);
64 static gboolean   avatar_chooser_drag_motion_cb        (GtkWidget            *widget,
65                                                         GdkDragContext       *context,
66                                                         gint                  x,
67                                                         gint                  y,
68                                                         guint                 time,
69                                                         EmpathyAvatarChooser *chooser);
70 static void       avatar_chooser_drag_leave_cb         (GtkWidget            *widget,
71                                                         GdkDragContext       *context,
72                                                         guint                 time,
73                                                         EmpathyAvatarChooser *chooser);
74 static gboolean   avatar_chooser_drag_drop_cb          (GtkWidget            *widget,
75                                                         GdkDragContext       *context,
76                                                         gint                  x,
77                                                         gint                  y,
78                                                         guint                 time,
79                                                         EmpathyAvatarChooser *chooser);
80 static void       avatar_chooser_drag_data_received_cb (GtkWidget            *widget,
81                                                         GdkDragContext       *context,
82                                                         gint                  x,
83                                                         gint                  y,
84                                                         GtkSelectionData     *selection_data,
85                                                         guint                 info,
86                                                         guint                 time,
87                                                         EmpathyAvatarChooser *chooser);
88 static void       avatar_chooser_clicked_cb            (GtkWidget            *button,
89                                                         EmpathyAvatarChooser *chooser);
90
91 enum {
92         CHANGED,
93         LAST_SIGNAL
94 };
95
96 enum {
97         PROP_0,
98         PROP_ACCOUNT
99 };
100
101 static guint signals [LAST_SIGNAL];
102
103 G_DEFINE_TYPE (EmpathyAvatarChooser, empathy_avatar_chooser, GTK_TYPE_BUTTON);
104
105 /*
106  * Drag and drop stuff
107  */
108 #define URI_LIST_TYPE "text/uri-list"
109
110 enum DndTargetType {
111         DND_TARGET_TYPE_URI_LIST
112 };
113
114 static const GtkTargetEntry drop_types[] = {
115         { URI_LIST_TYPE, 0, DND_TARGET_TYPE_URI_LIST },
116 };
117
118 static void
119 avatar_chooser_get_property (GObject    *object,
120                              guint       param_id,
121                              GValue     *value,
122                              GParamSpec *pspec)
123 {
124         EmpathyAvatarChooserPriv *priv = GET_PRIV (object);
125
126         switch (param_id) {
127         case PROP_ACCOUNT:
128                 g_value_set_object (value, priv->account);
129                 break;
130         default:
131                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
132                 break;
133         }
134 }
135
136 static void
137 avatar_chooser_set_property (GObject      *object,
138                              guint         param_id,
139                              const GValue *value,
140                              GParamSpec   *pspec)
141 {
142         EmpathyAvatarChooser *self = EMPATHY_AVATAR_CHOOSER (object);
143
144         switch (param_id) {
145         case PROP_ACCOUNT:
146                 avatar_chooser_set_account (self, g_value_get_object (value));
147                 break;
148         default:
149                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
150                 break;
151         }
152 }
153
154 static void
155 empathy_avatar_chooser_class_init (EmpathyAvatarChooserClass *klass)
156 {
157         GObjectClass *object_class = G_OBJECT_CLASS (klass);
158         GParamSpec *param_spec;
159
160         object_class->finalize = avatar_chooser_finalize;
161         object_class->get_property = avatar_chooser_get_property;
162         object_class->set_property = avatar_chooser_set_property;
163
164         signals[CHANGED] =
165                 g_signal_new ("changed",
166                               G_TYPE_FROM_CLASS (klass),
167                               G_SIGNAL_RUN_LAST,
168                               0,
169                               NULL, NULL,
170                               g_cclosure_marshal_VOID__VOID,
171                               G_TYPE_NONE, 0);
172
173         param_spec = g_param_spec_object ("account",
174                                           "McAccount",
175                                           "McAccount whose avatar should be "
176                                           "shown and modified by this widget",
177                                           MC_TYPE_ACCOUNT,
178                                           G_PARAM_READWRITE |
179                                           G_PARAM_STATIC_STRINGS);
180         g_object_class_install_property (object_class,
181                                          PROP_ACCOUNT,
182                                          param_spec);
183
184         g_type_class_add_private (object_class, sizeof (EmpathyAvatarChooserPriv));
185 }
186
187 static void
188 empathy_avatar_chooser_init (EmpathyAvatarChooser *chooser)
189 {
190         EmpathyAvatarChooserPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chooser,
191                 EMPATHY_TYPE_AVATAR_CHOOSER, EmpathyAvatarChooserPriv);
192
193         chooser->priv = priv;
194         gtk_drag_dest_set (GTK_WIDGET (chooser),
195                            GTK_DEST_DEFAULT_ALL,
196                            drop_types,
197                            G_N_ELEMENTS (drop_types),
198                            GDK_ACTION_COPY);
199
200         g_signal_connect (chooser, "drag-motion",
201                           G_CALLBACK (avatar_chooser_drag_motion_cb),
202                           chooser);
203         g_signal_connect (chooser, "drag-leave",
204                           G_CALLBACK (avatar_chooser_drag_leave_cb),
205                           chooser);
206         g_signal_connect (chooser, "drag-drop",
207                           G_CALLBACK (avatar_chooser_drag_drop_cb),
208                           chooser);
209         g_signal_connect (chooser, "drag-data-received",
210                           G_CALLBACK (avatar_chooser_drag_data_received_cb),
211                           chooser);
212         g_signal_connect (chooser, "clicked",
213                           G_CALLBACK (avatar_chooser_clicked_cb),
214                           chooser);
215
216         priv->contact_factory = empathy_contact_factory_new ();
217
218         empathy_avatar_chooser_set (chooser, NULL);
219 }
220
221 static void
222 avatar_chooser_finalize (GObject *object)
223 {
224         EmpathyAvatarChooserPriv *priv;
225
226         priv = GET_PRIV (object);
227
228         avatar_chooser_set_account (EMPATHY_AVATAR_CHOOSER (object), NULL);
229         g_assert (priv->account == NULL);
230         g_assert (priv->tp_contact_factory == NULL);
231
232         g_object_unref (priv->contact_factory);
233
234         if (priv->avatar != NULL) {
235                 empathy_avatar_unref (priv->avatar);
236         }
237
238         G_OBJECT_CLASS (empathy_avatar_chooser_parent_class)->finalize (object);
239 }
240
241 static void
242 avatar_chooser_tp_cf_ready_cb (EmpathyTpContactFactory *tp_cf,
243                                GParamSpec              *unused,
244                                EmpathyAvatarChooser    *self)
245 {
246         EmpathyAvatarChooserPriv *priv = GET_PRIV (self);
247         gboolean ready;
248
249         /* sanity check that we're listening on the right ETpCF */
250         g_assert (priv->tp_contact_factory == tp_cf);
251
252         ready = empathy_tp_contact_factory_is_ready (tp_cf);
253         gtk_widget_set_sensitive (GTK_WIDGET (self), ready);
254 }
255
256 static void
257 avatar_chooser_set_account (EmpathyAvatarChooser *self,
258                             McAccount            *account)
259 {
260         EmpathyAvatarChooserPriv *priv = GET_PRIV (self);
261
262         if (priv->account != NULL) {
263                 g_object_unref (priv->account);
264                 priv->account = NULL;
265
266                 g_assert (priv->tp_contact_factory != NULL);
267
268                 g_signal_handler_disconnect (priv->tp_contact_factory,
269                         priv->ready_handler_id);
270                 priv->ready_handler_id = 0;
271
272                 g_object_unref (priv->tp_contact_factory);
273                 priv->tp_contact_factory = NULL;
274         }
275
276         if (account != NULL) {
277                 priv->account = g_object_ref (account);
278                 priv->tp_contact_factory = g_object_ref (
279                         empathy_contact_factory_get_tp_factory (
280                                 priv->contact_factory, priv->account));
281
282                 priv->ready_handler_id = g_signal_connect (
283                         priv->tp_contact_factory, "notify::ready",
284                         G_CALLBACK (avatar_chooser_tp_cf_ready_cb), self);
285                 avatar_chooser_tp_cf_ready_cb (priv->tp_contact_factory, NULL,
286                         self);
287         }
288 }
289
290 static void
291 avatar_chooser_error_show (EmpathyAvatarChooser *chooser,
292                            const gchar          *primary_text,
293                            const gchar          *secondary_text)
294 {
295         GtkWidget *parent;
296         GtkWidget *dialog;
297
298         parent = gtk_widget_get_toplevel (GTK_WIDGET (chooser));
299         if (!GTK_IS_WINDOW (parent)) {
300                 parent = NULL;
301         }
302
303         dialog = gtk_message_dialog_new (parent ? GTK_WINDOW (parent) : NULL,
304                                          GTK_DIALOG_MODAL,
305                                          GTK_MESSAGE_WARNING,
306                                          GTK_BUTTONS_CLOSE,
307                                          "%s", primary_text);
308
309         if (secondary_text != NULL) {
310                 gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
311                                                           "%s", secondary_text);
312         }
313
314         g_signal_connect (dialog, "response",
315                           G_CALLBACK (gtk_widget_destroy), NULL);
316         gtk_widget_show (dialog);
317
318 }
319
320 static gboolean
321 str_in_strv (gchar  *str,
322              gchar **strv)
323 {
324         if (strv == NULL) {
325                 return FALSE;
326         }
327
328         while (*strv != NULL) {
329                 if (g_str_equal (str, *strv)) {
330                         return TRUE;
331                 }
332                 strv++;
333         }
334         return FALSE;
335 }
336
337 /* The caller must free the strings stored in satisfactory_format_name and
338  * satisfactory_mime_type.
339  */
340 static gboolean
341 can_satisfy_mime_type_requirements (gchar **accepted_mime_types,
342                                     gchar **satisfactory_format_name,
343                                     gchar **satisfactory_mime_type)
344 {
345         gchar *name = NULL;
346         gchar *type = NULL;
347
348         if (accepted_mime_types == NULL || *accepted_mime_types == NULL) {
349                 return FALSE;
350         }
351
352         /* Special-case png and jpeg to avoid accidentally saving to something
353          * uncompressed like bmp. This assumes that we can write image/png and
354          * image/jpeg; if this isn't true then something's really wrong with
355          * GdkPixbuf.
356          */
357         if (str_in_strv ("image/jpeg", accepted_mime_types)) {
358                 name = g_strdup ("jpeg");
359                 type = g_strdup ("image/jpeg");
360         } else if (str_in_strv ("image/png", accepted_mime_types)) {
361                 name = g_strdup ("png");
362                 type = g_strdup ("image/png");
363         } else {
364                 GSList  *formats, *l;
365                 gboolean found = FALSE;
366
367                 formats = gdk_pixbuf_get_formats ();
368                 for (l = formats; !found && l != NULL; l = l->next) {
369                         GdkPixbufFormat *format = l->data;
370                         gchar **format_mime_types;
371                         gchar **iter;
372
373                         if (!gdk_pixbuf_format_is_writable (format)) {
374                                 continue;
375                         }
376
377                         format_mime_types = gdk_pixbuf_format_get_mime_types (format);
378                         for (iter = format_mime_types; *iter != NULL; iter++) {
379                                 if (str_in_strv (*iter, accepted_mime_types)) {
380                                         name = gdk_pixbuf_format_get_name (format);
381                                         type = g_strdup (*iter);
382                                         found = TRUE;
383                                         break;
384                                 }
385                         }
386                         g_strfreev (format_mime_types);
387                 }
388
389                 g_slist_free (formats);
390         }
391
392         *satisfactory_format_name = name;
393         *satisfactory_mime_type = type;
394
395         return name != NULL;
396 }
397
398 static EmpathyAvatar *
399 avatar_chooser_maybe_convert_and_scale (EmpathyAvatarChooser *chooser,
400                                         GdkPixbuf            *pixbuf,
401                                         EmpathyAvatar        *avatar)
402 {
403         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
404         EmpathyTpContactFactory  *tp_cf = priv->tp_contact_factory;
405         gint                      max_width = 0, max_height = 0, max_size = 0;
406         gchar                   **mime_types = NULL;
407         gboolean                  needs_conversion = FALSE;
408         gint                      width, height;
409         gchar                    *new_format_name = NULL;
410         gchar                    *new_mime_type = NULL;
411         gdouble                   min_factor, max_factor;
412         gdouble                   factor;
413         gchar                    *converted_image_data = NULL;
414         gsize                     converted_image_size = 0;
415
416         /* This should only be called if the user is setting a new avatar,
417          * which should only be allowed once the avatar requirements have been
418          * discovered.
419          */
420         g_return_val_if_fail (tp_cf != NULL, NULL);
421         g_return_val_if_fail (empathy_tp_contact_factory_is_ready (tp_cf),
422                 NULL);
423
424         g_object_get (tp_cf,
425                 "avatar-mime-types", &mime_types, /* Needs g_strfreev-ing */
426                 "avatar-max-width", &max_width,
427                 "avatar-max-height", &max_height,
428                 "avatar-max-size", &max_size,
429                 NULL);
430
431         /* Smaller is the factor, smaller will be the image.
432          * 0 is an empty image, 1 is the full size. */
433         min_factor = 0;
434         max_factor = 1;
435         factor = 1;
436
437         if (!can_satisfy_mime_type_requirements (mime_types, &new_format_name,
438                                                  &new_mime_type)) {
439                 avatar_chooser_error_show (chooser,
440                         _("Can't convert to any acceptable format!"),
441                         NULL);
442                 g_strfreev (mime_types);
443                 return NULL;
444         }
445
446         /* If the avatar is not already in the right type, it needs converting. */
447         if (!str_in_strv (avatar->format, mime_types)) {
448                 DEBUG ("Image format %s not supported by the protocol",
449                         avatar->format);
450
451                 needs_conversion = TRUE;
452         }
453         g_strfreev (mime_types);
454
455         /* If width or height are too big, it needs converting. */
456         width = gdk_pixbuf_get_width (pixbuf);
457         height = gdk_pixbuf_get_height (pixbuf);
458         if ((max_width > 0 && width > max_width) ||
459             (max_height > 0 && height > max_height)) {
460                 gdouble h_factor, v_factor;
461
462                 h_factor = (gdouble) max_width / width;
463                 v_factor = (gdouble) max_height / height;
464                 factor = max_factor = MIN (h_factor, v_factor);
465
466                 DEBUG ("Image dimensions (%dx%d) are too big. Max is %dx%d.",
467                        width, height, max_width, max_height);
468
469                 needs_conversion = TRUE;
470         }
471
472         /* If the data len is too big and no other conversion is needed,
473          * try with a lower factor. */
474         if (max_size > 0 && avatar->len > max_size && !needs_conversion) {
475                 DEBUG ("Image data (%"G_GSIZE_FORMAT" bytes) is too big "
476                        "(max is %"G_GSIZE_FORMAT" bytes), conversion needed.",
477                        avatar->len, max_size);
478
479                 factor = 0.5;
480                 needs_conversion = TRUE;
481         }
482
483         /* If no conversion is needed, return the avatar */
484         if (!needs_conversion) {
485                 g_free (new_format_name);
486                 g_free (new_mime_type);
487                 return empathy_avatar_ref (avatar);
488         }
489
490         do {
491                 GdkPixbuf *pixbuf_scaled = NULL;
492                 gboolean   saved;
493                 gint       new_width, new_height;
494                 GError    *error = NULL;
495
496                 g_free (converted_image_data);
497
498                 if (factor != 1) {
499                         new_width = width * factor;
500                         new_height = height * factor;
501                         pixbuf_scaled = gdk_pixbuf_scale_simple (pixbuf,
502                                                                  new_width,
503                                                                  new_height,
504                                                                  GDK_INTERP_HYPER);
505                 } else {
506                         new_width = width;
507                         new_height = height;
508                         pixbuf_scaled = g_object_ref (pixbuf);
509                 }
510
511                 DEBUG ("Trying with factor %f (%dx%d) and format %s...", factor,
512                         new_width, new_height, new_format_name);
513
514                 saved = gdk_pixbuf_save_to_buffer (pixbuf_scaled,
515                                                    &converted_image_data,
516                                                    &converted_image_size,
517                                                    new_format_name,
518                                                    &error, NULL);
519
520                 if (!saved) {
521                         g_free (new_format_name);
522                         g_free (new_mime_type);
523                         avatar_chooser_error_show (chooser,
524                                 _("Couldn't convert image"),
525                                 error ? error->message : NULL);
526                         g_clear_error (&error);
527                         return NULL;
528                 }
529
530                 DEBUG ("Produced an image data of %"G_GSIZE_FORMAT" bytes.",
531                         converted_image_size);
532
533                 if (max_size == 0)
534                         break;
535
536                 /* Make a binary search for the bigest factor that produce
537                  * an image data size less than max_size */
538                 if (converted_image_size > max_size)
539                         max_factor = factor;
540                 if (converted_image_size < max_size)
541                         min_factor = factor;
542                 factor = min_factor + (max_factor - min_factor)/2;
543
544                 /* We are done if either:
545                  * - min_factor == max_factor. That happens if we resized to
546                  *   the max required dimension and the produced data size is
547                  *   less than max_size.
548                  * - The data size is close enough to max_size. Here we accept
549                  *   a difference of 1k.
550                  */
551         } while (min_factor != max_factor &&
552                  ABS (max_size - converted_image_size) > 1024);
553         g_free (new_format_name);
554
555         /* Takes ownership of new_mime_type and converted_image_data */
556         avatar = empathy_avatar_new (converted_image_data,
557                 converted_image_size, new_mime_type, NULL);
558
559         return avatar;
560 }
561
562 static void
563 avatar_chooser_clear_image (EmpathyAvatarChooser *chooser)
564 {
565         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
566         GtkWidget *image;
567
568         if (priv->avatar == NULL) {
569                 return;
570         }
571
572         empathy_avatar_unref (priv->avatar);
573         priv->avatar = NULL;
574
575         image = gtk_image_new_from_icon_name ("stock_person", GTK_ICON_SIZE_DIALOG);
576         gtk_button_set_image (GTK_BUTTON (chooser), image);
577         g_signal_emit (chooser, signals[CHANGED], 0);
578 }
579
580 static void
581 avatar_chooser_set_image_from_data (EmpathyAvatarChooser *chooser,
582                                     gchar                *data,
583                                     gsize                 size,
584                                     gboolean              set_locally)
585 {
586         GdkPixbuf     *pixbuf;
587         EmpathyAvatar *avatar = NULL;
588         gchar         *mime_type = NULL;
589
590         if (data == NULL) {
591                 avatar_chooser_clear_image (chooser);
592                 return;
593         }
594
595         pixbuf = empathy_pixbuf_from_data_and_mime (data, size, &mime_type);
596         if (pixbuf == NULL) {
597                 g_free (data);
598                 return;
599         }
600
601         /* avatar takes ownership of data and mime_type */
602         avatar = empathy_avatar_new (data, size, mime_type, NULL);
603
604         avatar_chooser_set_image (chooser, avatar, pixbuf, set_locally);
605 }
606
607 static void
608 avatar_chooser_set_image_from_avatar (EmpathyAvatarChooser *chooser,
609                                       EmpathyAvatar        *avatar,
610                                       gboolean              set_locally)
611 {
612         GdkPixbuf *pixbuf;
613         gchar     *mime_type = NULL;
614
615         g_assert (avatar != NULL);
616
617         pixbuf = empathy_pixbuf_from_data_and_mime (avatar->data,
618                                                     avatar->len,
619                                                     &mime_type);
620         if (pixbuf == NULL) {
621                 DEBUG ("couldn't make a pixbuf from avatar; giving up");
622                 return;
623         }
624
625         if (avatar->format == NULL) {
626                 avatar->format = mime_type;
627         } else {
628                 if (strcmp (mime_type, avatar->format)) {
629                         DEBUG ("avatar->format is %s; gdkpixbuf yields %s!",
630                                 avatar->format, mime_type);
631                 }
632                 g_free (mime_type);
633         }
634
635         empathy_avatar_ref (avatar);
636
637         avatar_chooser_set_image (chooser, avatar, pixbuf, set_locally);
638 }
639
640 static void
641 avatar_chooser_set_image (EmpathyAvatarChooser *chooser,
642                           EmpathyAvatar        *avatar,
643                           GdkPixbuf            *pixbuf,
644                           gboolean              set_locally)
645 {
646         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
647         GdkPixbuf                *pixbuf_view;
648         GtkWidget                *image;
649
650         g_assert (avatar != NULL);
651         g_assert (pixbuf != NULL);
652
653         if (set_locally) {
654                 EmpathyAvatar *conv;
655
656                 conv = avatar_chooser_maybe_convert_and_scale (chooser,
657                         pixbuf, avatar);
658                 empathy_avatar_unref (avatar);
659
660                 if (conv == NULL) {
661                         /* An error occured; don't change the avatar. */
662                         return;
663                 }
664
665                 avatar = conv;
666         }
667
668         if (priv->avatar != NULL) {
669                 empathy_avatar_unref (priv->avatar);
670         }
671         priv->avatar = avatar;
672
673         pixbuf_view = empathy_pixbuf_scale_down_if_necessary (pixbuf, AVATAR_SIZE_VIEW);
674         image = gtk_image_new_from_pixbuf (pixbuf_view);
675
676         gtk_button_set_image (GTK_BUTTON (chooser), image);
677         g_signal_emit (chooser, signals[CHANGED], 0);
678
679         g_object_unref (pixbuf_view);
680         g_object_unref (pixbuf);
681 }
682
683 static void
684 avatar_chooser_set_image_from_file (EmpathyAvatarChooser *chooser,
685                                     const gchar          *filename)
686 {
687         gchar  *image_data = NULL;
688         gsize   image_size = 0;
689         GError *error = NULL;
690
691         if (!g_file_get_contents (filename, &image_data, &image_size, &error)) {
692                 DEBUG ("Failed to load image from '%s': %s", filename,
693                         error ? error->message : "No error given");
694
695                 g_clear_error (&error);
696                 return;
697         }
698
699         avatar_chooser_set_image_from_data (chooser, image_data, image_size, TRUE);
700 }
701
702 static gboolean
703 avatar_chooser_drag_motion_cb (GtkWidget          *widget,
704                               GdkDragContext     *context,
705                               gint                x,
706                               gint                y,
707                               guint               time,
708                               EmpathyAvatarChooser *chooser)
709 {
710         EmpathyAvatarChooserPriv *priv;
711         GList                  *p;
712
713         priv = GET_PRIV (chooser);
714
715         for (p = context->targets; p != NULL; p = p->next) {
716                 gchar *possible_type;
717
718                 possible_type = gdk_atom_name (GDK_POINTER_TO_ATOM (p->data));
719
720                 if (!strcmp (possible_type, URI_LIST_TYPE)) {
721                         g_free (possible_type);
722                         gdk_drag_status (context, GDK_ACTION_COPY, time);
723
724                         return TRUE;
725                 }
726
727                 g_free (possible_type);
728         }
729
730         return FALSE;
731 }
732
733 static void
734 avatar_chooser_drag_leave_cb (GtkWidget          *widget,
735                              GdkDragContext     *context,
736                              guint               time,
737                              EmpathyAvatarChooser *chooser)
738 {
739 }
740
741 static gboolean
742 avatar_chooser_drag_drop_cb (GtkWidget          *widget,
743                             GdkDragContext     *context,
744                             gint                x,
745                             gint                y,
746                             guint               time,
747                             EmpathyAvatarChooser *chooser)
748 {
749         EmpathyAvatarChooserPriv *priv;
750         GList                  *p;
751
752         priv = GET_PRIV (chooser);
753
754         if (context->targets == NULL) {
755                 return FALSE;
756         }
757
758         for (p = context->targets; p != NULL; p = p->next) {
759                 char *possible_type;
760
761                 possible_type = gdk_atom_name (GDK_POINTER_TO_ATOM (p->data));
762                 if (!strcmp (possible_type, URI_LIST_TYPE)) {
763                         g_free (possible_type);
764                         gtk_drag_get_data (widget, context,
765                                            GDK_POINTER_TO_ATOM (p->data),
766                                            time);
767
768                         return TRUE;
769                 }
770
771                 g_free (possible_type);
772         }
773
774         return FALSE;
775 }
776
777 static void
778 avatar_chooser_drag_data_received_cb (GtkWidget          *widget,
779                                      GdkDragContext     *context,
780                                      gint                x,
781                                      gint                y,
782                                      GtkSelectionData   *selection_data,
783                                      guint               info,
784                                      guint               time,
785                                      EmpathyAvatarChooser *chooser)
786 {
787         gchar    *target_type;
788         gboolean  handled = FALSE;
789
790         target_type = gdk_atom_name (selection_data->target);
791         if (!strcmp (target_type, URI_LIST_TYPE)) {
792                 GFile            *file;
793                 GFileInputStream *input_stream;
794                 gchar            *nl;
795                 gchar            *data = NULL;
796
797                 nl = strstr (selection_data->data, "\r\n");
798                 if (nl) {
799                         gchar *uri;
800
801                         uri = g_strndup (selection_data->data,
802                                          nl - (gchar*) selection_data->data);
803
804                         file = g_file_new_for_uri (uri);
805                         g_free (uri);
806                 } else {
807                         file = g_file_new_for_uri (selection_data->data);
808                 }
809
810                 input_stream = g_file_read (file, NULL, NULL);
811
812                 if (input_stream != NULL) {
813                         GFileInfo *info;
814                         
815                         info = g_file_query_info (file,
816                                                   G_FILE_ATTRIBUTE_STANDARD_SIZE,
817                                                   0, NULL, NULL);
818                         if (info != NULL) {
819                                 goffset size;
820                                 gssize bytes_read;
821                                 
822                                 size = g_file_info_get_size (info);
823                                 data = g_malloc (size);
824
825                                 bytes_read = g_input_stream_read (G_INPUT_STREAM (input_stream),
826                                                                   data, size,
827                                                                   NULL, NULL);
828                                 if (bytes_read != -1) {
829                                         avatar_chooser_set_image_from_data (
830                                                 chooser, data,
831                                                 (gsize) bytes_read,
832                                                 TRUE);
833                                         handled = TRUE;
834                                 }
835
836                                 g_free (data);
837                                 g_object_unref (info);
838                         }
839
840                         g_object_unref (input_stream);
841                 }
842                 
843                 g_object_unref (file);
844         }
845
846         gtk_drag_finish (context, handled, FALSE, time);
847 }
848
849 static void
850 avatar_chooser_update_preview_cb (GtkFileChooser       *file_chooser,
851                                   EmpathyAvatarChooser *chooser)
852 {
853         gchar *filename;
854
855         filename = gtk_file_chooser_get_preview_filename (file_chooser);
856
857         if (filename) {
858                 GtkWidget *image;
859                 GdkPixbuf *pixbuf = NULL;
860                 GdkPixbuf *scaled_pixbuf;
861
862                 pixbuf = gdk_pixbuf_new_from_file (filename, NULL);
863
864                 image = gtk_file_chooser_get_preview_widget (file_chooser);
865
866                 if (pixbuf) {
867                         scaled_pixbuf = empathy_pixbuf_scale_down_if_necessary (pixbuf, AVATAR_SIZE_SAVE);
868                         gtk_image_set_from_pixbuf (GTK_IMAGE (image), scaled_pixbuf);
869                         g_object_unref (scaled_pixbuf);
870                         g_object_unref (pixbuf);
871                 } else {
872                         gtk_image_set_from_stock (GTK_IMAGE (image),
873                                                   "gtk-dialog-question",
874                                                   GTK_ICON_SIZE_DIALOG);
875                 }
876         }
877
878         gtk_file_chooser_set_preview_widget_active (file_chooser, TRUE);
879 }
880
881 static void
882 avatar_chooser_response_cb (GtkWidget            *widget,
883                             gint                  response,
884                             EmpathyAvatarChooser *chooser)
885 {
886         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
887
888         if (response == GTK_RESPONSE_CANCEL) {
889                 goto out;
890         }
891
892         /* Check if we went non-ready since displaying the dialog. */
893         if (!empathy_tp_contact_factory_is_ready (priv->tp_contact_factory)) {
894                 DEBUG ("Can't set avatar when contact factory isn't ready.");
895                 goto out;
896         }
897
898         if (response == GTK_RESPONSE_OK) {
899                 gchar *filename;
900                 gchar *path;
901
902                 filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (widget));
903                 avatar_chooser_set_image_from_file (chooser, filename);
904                 g_free (filename);
905
906                 path = gtk_file_chooser_get_current_folder (GTK_FILE_CHOOSER (widget));
907                 if (path) {
908                         empathy_conf_set_string (empathy_conf_get (),
909                                                  EMPATHY_PREFS_UI_AVATAR_DIRECTORY,
910                                                  path);
911                         g_free (path);
912                 }
913         }
914         else if (response == GTK_RESPONSE_NO) {
915                 /* This corresponds to "No Image", not to "Cancel" */
916                 avatar_chooser_clear_image (chooser);
917         }
918
919 out:
920         gtk_widget_destroy (widget);
921 }
922
923 static void
924 avatar_chooser_clicked_cb (GtkWidget            *button,
925                            EmpathyAvatarChooser *chooser)
926 {
927         GtkFileChooser *chooser_dialog;
928         GtkWidget      *image;
929         gchar          *saved_dir = NULL;
930         const gchar    *default_dir = DEFAULT_DIR;
931         const gchar    *pics_dir;
932         GtkFileFilter  *filter;
933
934         chooser_dialog = GTK_FILE_CHOOSER (
935                 gtk_file_chooser_dialog_new (_("Select Your Avatar Image"),
936                                              empathy_get_toplevel_window (GTK_WIDGET (chooser)),
937                                              GTK_FILE_CHOOSER_ACTION_OPEN,
938                                              _("No Image"),
939                                              GTK_RESPONSE_NO,
940                                              GTK_STOCK_CANCEL,
941                                              GTK_RESPONSE_CANCEL,
942                                              GTK_STOCK_OPEN,
943                                              GTK_RESPONSE_OK,
944                                              NULL));
945
946         /* Get special dirs */
947         empathy_conf_get_string (empathy_conf_get (),
948                                  EMPATHY_PREFS_UI_AVATAR_DIRECTORY,
949                                  &saved_dir);
950         if (saved_dir && !g_file_test (saved_dir, G_FILE_TEST_IS_DIR)) {
951                 g_free (saved_dir);
952                 saved_dir = NULL;
953         }
954         if (!g_file_test (default_dir, G_FILE_TEST_IS_DIR)) {
955                 default_dir = NULL;
956         }
957         pics_dir = g_get_user_special_dir (G_USER_DIRECTORY_PICTURES);
958         if (pics_dir && !g_file_test (pics_dir, G_FILE_TEST_IS_DIR)) {
959                 pics_dir = NULL;
960         }
961
962         /* Set current dir to the last one or to DEFAULT_DIR or to home */
963         if (saved_dir) {
964                 gtk_file_chooser_set_current_folder (chooser_dialog, saved_dir);
965         }
966         else if (pics_dir) {
967                 gtk_file_chooser_set_current_folder (chooser_dialog, pics_dir);
968         }
969         else if (default_dir) {
970                 gtk_file_chooser_set_current_folder (chooser_dialog, default_dir);
971         } else {
972                 gtk_file_chooser_set_current_folder (chooser_dialog, g_get_home_dir ());
973         }
974
975         /* Add shortcuts to special dirs */
976         if (saved_dir) {
977                 gtk_file_chooser_add_shortcut_folder (chooser_dialog, saved_dir, NULL);
978         }
979         else if (pics_dir) {
980                 gtk_file_chooser_add_shortcut_folder (chooser_dialog, pics_dir, NULL);
981         }
982         if (default_dir) {
983                 gtk_file_chooser_add_shortcut_folder (chooser_dialog, default_dir, NULL);
984         }
985
986         /* Setup preview image */
987         image = gtk_image_new ();
988         gtk_file_chooser_set_preview_widget (chooser_dialog, image);
989         gtk_widget_set_size_request (image, AVATAR_SIZE_SAVE, AVATAR_SIZE_SAVE);
990         gtk_widget_show (image);
991         gtk_file_chooser_set_use_preview_label (chooser_dialog, FALSE);
992         g_signal_connect (chooser_dialog, "update-preview",
993                           G_CALLBACK (avatar_chooser_update_preview_cb),
994                           chooser);
995
996         /* Setup filers */
997         filter = gtk_file_filter_new ();
998         gtk_file_filter_set_name (filter, _("Images"));
999         gtk_file_filter_add_pixbuf_formats (filter);
1000         gtk_file_chooser_add_filter (chooser_dialog, filter);
1001         filter = gtk_file_filter_new ();
1002         gtk_file_filter_set_name (filter, _("All Files"));
1003         gtk_file_filter_add_pattern(filter, "*");
1004         gtk_file_chooser_add_filter (chooser_dialog, filter);
1005
1006         /* Setup response */
1007         gtk_dialog_set_default_response (GTK_DIALOG (chooser_dialog), GTK_RESPONSE_OK);
1008         g_signal_connect (chooser_dialog, "response",
1009                           G_CALLBACK (avatar_chooser_response_cb),
1010                           chooser);
1011
1012         gtk_widget_show (GTK_WIDGET (chooser_dialog));
1013         g_free (saved_dir);
1014 }
1015
1016 GtkWidget *
1017 empathy_avatar_chooser_new ()
1018 {
1019         return g_object_new (EMPATHY_TYPE_AVATAR_CHOOSER, NULL);
1020 }
1021
1022 void
1023 empathy_avatar_chooser_set (EmpathyAvatarChooser *chooser,
1024                             EmpathyAvatar        *avatar)
1025 {
1026         g_return_if_fail (EMPATHY_IS_AVATAR_CHOOSER (chooser));
1027
1028         if (avatar != NULL) {
1029                 avatar_chooser_set_image_from_avatar (chooser, avatar, FALSE);
1030         } else {
1031                 avatar_chooser_clear_image (chooser);
1032         }
1033 }
1034
1035 void
1036 empathy_avatar_chooser_get_image_data (EmpathyAvatarChooser  *chooser,
1037                                        const gchar          **data,
1038                                        gsize                 *data_size,
1039                                        const gchar          **mime_type)
1040 {
1041         EmpathyAvatarChooserPriv *priv;
1042
1043         g_return_if_fail (EMPATHY_IS_AVATAR_CHOOSER (chooser));
1044
1045         priv = GET_PRIV (chooser);
1046
1047         if (priv->avatar != NULL) {
1048                 if (data != NULL) {
1049                         *data = priv->avatar->data;
1050                 }
1051                 if (data_size != NULL) {
1052                         *data_size = priv->avatar->len;
1053                 }
1054                 if (mime_type != NULL) {
1055                         *mime_type = priv->avatar->format;
1056                 }
1057         } else {
1058                 if (data != NULL) {
1059                         *data = NULL;
1060                 }
1061                 if (data_size != NULL) {
1062                         *data_size = 0;
1063                 }
1064                 if (mime_type != NULL) {
1065                         *mime_type = NULL;
1066                 }
1067         }
1068 }
1069