]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-avatar-chooser.c
Improve error message.
[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                         _("Couldn't convert image"),
441                         _("None of the accepted image formats is supported on "
442                           "your system"));
443                 g_strfreev (mime_types);
444                 return NULL;
445         }
446
447         /* If the avatar is not already in the right type, it needs converting. */
448         if (!str_in_strv (avatar->format, mime_types)) {
449                 DEBUG ("Image format %s not supported by the protocol",
450                         avatar->format);
451
452                 needs_conversion = TRUE;
453         }
454         g_strfreev (mime_types);
455
456         /* If width or height are too big, it needs converting. */
457         width = gdk_pixbuf_get_width (pixbuf);
458         height = gdk_pixbuf_get_height (pixbuf);
459         if ((max_width > 0 && width > max_width) ||
460             (max_height > 0 && height > max_height)) {
461                 gdouble h_factor, v_factor;
462
463                 h_factor = (gdouble) max_width / width;
464                 v_factor = (gdouble) max_height / height;
465                 factor = max_factor = MIN (h_factor, v_factor);
466
467                 DEBUG ("Image dimensions (%dx%d) are too big. Max is %dx%d.",
468                        width, height, max_width, max_height);
469
470                 needs_conversion = TRUE;
471         }
472
473         /* If the data len is too big and no other conversion is needed,
474          * try with a lower factor. */
475         if (max_size > 0 && avatar->len > max_size && !needs_conversion) {
476                 DEBUG ("Image data (%"G_GSIZE_FORMAT" bytes) is too big "
477                        "(max is %"G_GSIZE_FORMAT" bytes), conversion needed.",
478                        avatar->len, max_size);
479
480                 factor = 0.5;
481                 needs_conversion = TRUE;
482         }
483
484         /* If no conversion is needed, return the avatar */
485         if (!needs_conversion) {
486                 g_free (new_format_name);
487                 g_free (new_mime_type);
488                 return empathy_avatar_ref (avatar);
489         }
490
491         do {
492                 GdkPixbuf *pixbuf_scaled = NULL;
493                 gboolean   saved;
494                 gint       new_width, new_height;
495                 GError    *error = NULL;
496
497                 g_free (converted_image_data);
498
499                 if (factor != 1) {
500                         new_width = width * factor;
501                         new_height = height * factor;
502                         pixbuf_scaled = gdk_pixbuf_scale_simple (pixbuf,
503                                                                  new_width,
504                                                                  new_height,
505                                                                  GDK_INTERP_HYPER);
506                 } else {
507                         new_width = width;
508                         new_height = height;
509                         pixbuf_scaled = g_object_ref (pixbuf);
510                 }
511
512                 DEBUG ("Trying with factor %f (%dx%d) and format %s...", factor,
513                         new_width, new_height, new_format_name);
514
515                 saved = gdk_pixbuf_save_to_buffer (pixbuf_scaled,
516                                                    &converted_image_data,
517                                                    &converted_image_size,
518                                                    new_format_name,
519                                                    &error, NULL);
520
521                 if (!saved) {
522                         g_free (new_format_name);
523                         g_free (new_mime_type);
524                         avatar_chooser_error_show (chooser,
525                                 _("Couldn't convert image"),
526                                 error ? error->message : NULL);
527                         g_clear_error (&error);
528                         return NULL;
529                 }
530
531                 DEBUG ("Produced an image data of %"G_GSIZE_FORMAT" bytes.",
532                         converted_image_size);
533
534                 if (max_size == 0)
535                         break;
536
537                 /* Make a binary search for the bigest factor that produce
538                  * an image data size less than max_size */
539                 if (converted_image_size > max_size)
540                         max_factor = factor;
541                 if (converted_image_size < max_size)
542                         min_factor = factor;
543                 factor = min_factor + (max_factor - min_factor)/2;
544
545                 /* We are done if either:
546                  * - min_factor == max_factor. That happens if we resized to
547                  *   the max required dimension and the produced data size is
548                  *   less than max_size.
549                  * - The data size is close enough to max_size. Here we accept
550                  *   a difference of 1k.
551                  */
552         } while (min_factor != max_factor &&
553                  ABS (max_size - converted_image_size) > 1024);
554         g_free (new_format_name);
555
556         /* Takes ownership of new_mime_type and converted_image_data */
557         avatar = empathy_avatar_new (converted_image_data,
558                 converted_image_size, new_mime_type, NULL);
559
560         return avatar;
561 }
562
563 static void
564 avatar_chooser_clear_image (EmpathyAvatarChooser *chooser)
565 {
566         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
567         GtkWidget *image;
568
569         if (priv->avatar == NULL) {
570                 return;
571         }
572
573         empathy_avatar_unref (priv->avatar);
574         priv->avatar = NULL;
575
576         image = gtk_image_new_from_icon_name ("stock_person", GTK_ICON_SIZE_DIALOG);
577         gtk_button_set_image (GTK_BUTTON (chooser), image);
578         g_signal_emit (chooser, signals[CHANGED], 0);
579 }
580
581 static void
582 avatar_chooser_set_image_from_data (EmpathyAvatarChooser *chooser,
583                                     gchar                *data,
584                                     gsize                 size,
585                                     gboolean              set_locally)
586 {
587         GdkPixbuf     *pixbuf;
588         EmpathyAvatar *avatar = NULL;
589         gchar         *mime_type = NULL;
590
591         if (data == NULL) {
592                 avatar_chooser_clear_image (chooser);
593                 return;
594         }
595
596         pixbuf = empathy_pixbuf_from_data_and_mime (data, size, &mime_type);
597         if (pixbuf == NULL) {
598                 g_free (data);
599                 return;
600         }
601
602         /* avatar takes ownership of data and mime_type */
603         avatar = empathy_avatar_new (data, size, mime_type, NULL);
604
605         avatar_chooser_set_image (chooser, avatar, pixbuf, set_locally);
606 }
607
608 static void
609 avatar_chooser_set_image_from_avatar (EmpathyAvatarChooser *chooser,
610                                       EmpathyAvatar        *avatar,
611                                       gboolean              set_locally)
612 {
613         GdkPixbuf *pixbuf;
614         gchar     *mime_type = NULL;
615
616         g_assert (avatar != NULL);
617
618         pixbuf = empathy_pixbuf_from_data_and_mime (avatar->data,
619                                                     avatar->len,
620                                                     &mime_type);
621         if (pixbuf == NULL) {
622                 DEBUG ("couldn't make a pixbuf from avatar; giving up");
623                 return;
624         }
625
626         if (avatar->format == NULL) {
627                 avatar->format = mime_type;
628         } else {
629                 if (strcmp (mime_type, avatar->format)) {
630                         DEBUG ("avatar->format is %s; gdkpixbuf yields %s!",
631                                 avatar->format, mime_type);
632                 }
633                 g_free (mime_type);
634         }
635
636         empathy_avatar_ref (avatar);
637
638         avatar_chooser_set_image (chooser, avatar, pixbuf, set_locally);
639 }
640
641 static void
642 avatar_chooser_set_image (EmpathyAvatarChooser *chooser,
643                           EmpathyAvatar        *avatar,
644                           GdkPixbuf            *pixbuf,
645                           gboolean              set_locally)
646 {
647         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
648         GdkPixbuf                *pixbuf_view;
649         GtkWidget                *image;
650
651         g_assert (avatar != NULL);
652         g_assert (pixbuf != NULL);
653
654         if (set_locally) {
655                 EmpathyAvatar *conv;
656
657                 conv = avatar_chooser_maybe_convert_and_scale (chooser,
658                         pixbuf, avatar);
659                 empathy_avatar_unref (avatar);
660
661                 if (conv == NULL) {
662                         /* An error occured; don't change the avatar. */
663                         return;
664                 }
665
666                 avatar = conv;
667         }
668
669         if (priv->avatar != NULL) {
670                 empathy_avatar_unref (priv->avatar);
671         }
672         priv->avatar = avatar;
673
674         pixbuf_view = empathy_pixbuf_scale_down_if_necessary (pixbuf, AVATAR_SIZE_VIEW);
675         image = gtk_image_new_from_pixbuf (pixbuf_view);
676
677         gtk_button_set_image (GTK_BUTTON (chooser), image);
678         g_signal_emit (chooser, signals[CHANGED], 0);
679
680         g_object_unref (pixbuf_view);
681         g_object_unref (pixbuf);
682 }
683
684 static void
685 avatar_chooser_set_image_from_file (EmpathyAvatarChooser *chooser,
686                                     const gchar          *filename)
687 {
688         gchar  *image_data = NULL;
689         gsize   image_size = 0;
690         GError *error = NULL;
691
692         if (!g_file_get_contents (filename, &image_data, &image_size, &error)) {
693                 DEBUG ("Failed to load image from '%s': %s", filename,
694                         error ? error->message : "No error given");
695
696                 g_clear_error (&error);
697                 return;
698         }
699
700         avatar_chooser_set_image_from_data (chooser, image_data, image_size, TRUE);
701 }
702
703 static gboolean
704 avatar_chooser_drag_motion_cb (GtkWidget          *widget,
705                               GdkDragContext     *context,
706                               gint                x,
707                               gint                y,
708                               guint               time,
709                               EmpathyAvatarChooser *chooser)
710 {
711         EmpathyAvatarChooserPriv *priv;
712         GList                  *p;
713
714         priv = GET_PRIV (chooser);
715
716         for (p = context->targets; p != NULL; p = p->next) {
717                 gchar *possible_type;
718
719                 possible_type = gdk_atom_name (GDK_POINTER_TO_ATOM (p->data));
720
721                 if (!strcmp (possible_type, URI_LIST_TYPE)) {
722                         g_free (possible_type);
723                         gdk_drag_status (context, GDK_ACTION_COPY, time);
724
725                         return TRUE;
726                 }
727
728                 g_free (possible_type);
729         }
730
731         return FALSE;
732 }
733
734 static void
735 avatar_chooser_drag_leave_cb (GtkWidget          *widget,
736                              GdkDragContext     *context,
737                              guint               time,
738                              EmpathyAvatarChooser *chooser)
739 {
740 }
741
742 static gboolean
743 avatar_chooser_drag_drop_cb (GtkWidget          *widget,
744                             GdkDragContext     *context,
745                             gint                x,
746                             gint                y,
747                             guint               time,
748                             EmpathyAvatarChooser *chooser)
749 {
750         EmpathyAvatarChooserPriv *priv;
751         GList                  *p;
752
753         priv = GET_PRIV (chooser);
754
755         if (context->targets == NULL) {
756                 return FALSE;
757         }
758
759         for (p = context->targets; p != NULL; p = p->next) {
760                 char *possible_type;
761
762                 possible_type = gdk_atom_name (GDK_POINTER_TO_ATOM (p->data));
763                 if (!strcmp (possible_type, URI_LIST_TYPE)) {
764                         g_free (possible_type);
765                         gtk_drag_get_data (widget, context,
766                                            GDK_POINTER_TO_ATOM (p->data),
767                                            time);
768
769                         return TRUE;
770                 }
771
772                 g_free (possible_type);
773         }
774
775         return FALSE;
776 }
777
778 static void
779 avatar_chooser_drag_data_received_cb (GtkWidget          *widget,
780                                      GdkDragContext     *context,
781                                      gint                x,
782                                      gint                y,
783                                      GtkSelectionData   *selection_data,
784                                      guint               info,
785                                      guint               time,
786                                      EmpathyAvatarChooser *chooser)
787 {
788         gchar    *target_type;
789         gboolean  handled = FALSE;
790
791         target_type = gdk_atom_name (selection_data->target);
792         if (!strcmp (target_type, URI_LIST_TYPE)) {
793                 GFile            *file;
794                 GFileInputStream *input_stream;
795                 gchar            *nl;
796                 gchar            *data = NULL;
797
798                 nl = strstr (selection_data->data, "\r\n");
799                 if (nl) {
800                         gchar *uri;
801
802                         uri = g_strndup (selection_data->data,
803                                          nl - (gchar*) selection_data->data);
804
805                         file = g_file_new_for_uri (uri);
806                         g_free (uri);
807                 } else {
808                         file = g_file_new_for_uri (selection_data->data);
809                 }
810
811                 input_stream = g_file_read (file, NULL, NULL);
812
813                 if (input_stream != NULL) {
814                         GFileInfo *info;
815                         
816                         info = g_file_query_info (file,
817                                                   G_FILE_ATTRIBUTE_STANDARD_SIZE,
818                                                   0, NULL, NULL);
819                         if (info != NULL) {
820                                 goffset size;
821                                 gssize bytes_read;
822                                 
823                                 size = g_file_info_get_size (info);
824                                 data = g_malloc (size);
825
826                                 bytes_read = g_input_stream_read (G_INPUT_STREAM (input_stream),
827                                                                   data, size,
828                                                                   NULL, NULL);
829                                 if (bytes_read != -1) {
830                                         avatar_chooser_set_image_from_data (
831                                                 chooser, data,
832                                                 (gsize) bytes_read,
833                                                 TRUE);
834                                         handled = TRUE;
835                                 }
836
837                                 g_free (data);
838                                 g_object_unref (info);
839                         }
840
841                         g_object_unref (input_stream);
842                 }
843                 
844                 g_object_unref (file);
845         }
846
847         gtk_drag_finish (context, handled, FALSE, time);
848 }
849
850 static void
851 avatar_chooser_update_preview_cb (GtkFileChooser       *file_chooser,
852                                   EmpathyAvatarChooser *chooser)
853 {
854         gchar *filename;
855
856         filename = gtk_file_chooser_get_preview_filename (file_chooser);
857
858         if (filename) {
859                 GtkWidget *image;
860                 GdkPixbuf *pixbuf = NULL;
861                 GdkPixbuf *scaled_pixbuf;
862
863                 pixbuf = gdk_pixbuf_new_from_file (filename, NULL);
864
865                 image = gtk_file_chooser_get_preview_widget (file_chooser);
866
867                 if (pixbuf) {
868                         scaled_pixbuf = empathy_pixbuf_scale_down_if_necessary (pixbuf, AVATAR_SIZE_SAVE);
869                         gtk_image_set_from_pixbuf (GTK_IMAGE (image), scaled_pixbuf);
870                         g_object_unref (scaled_pixbuf);
871                         g_object_unref (pixbuf);
872                 } else {
873                         gtk_image_set_from_stock (GTK_IMAGE (image),
874                                                   "gtk-dialog-question",
875                                                   GTK_ICON_SIZE_DIALOG);
876                 }
877         }
878
879         gtk_file_chooser_set_preview_widget_active (file_chooser, TRUE);
880 }
881
882 static void
883 avatar_chooser_response_cb (GtkWidget            *widget,
884                             gint                  response,
885                             EmpathyAvatarChooser *chooser)
886 {
887         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
888
889         if (response == GTK_RESPONSE_CANCEL) {
890                 goto out;
891         }
892
893         /* Check if we went non-ready since displaying the dialog. */
894         if (!empathy_tp_contact_factory_is_ready (priv->tp_contact_factory)) {
895                 DEBUG ("Can't set avatar when contact factory isn't ready.");
896                 goto out;
897         }
898
899         if (response == GTK_RESPONSE_OK) {
900                 gchar *filename;
901                 gchar *path;
902
903                 filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (widget));
904                 avatar_chooser_set_image_from_file (chooser, filename);
905                 g_free (filename);
906
907                 path = gtk_file_chooser_get_current_folder (GTK_FILE_CHOOSER (widget));
908                 if (path) {
909                         empathy_conf_set_string (empathy_conf_get (),
910                                                  EMPATHY_PREFS_UI_AVATAR_DIRECTORY,
911                                                  path);
912                         g_free (path);
913                 }
914         }
915         else if (response == GTK_RESPONSE_NO) {
916                 /* This corresponds to "No Image", not to "Cancel" */
917                 avatar_chooser_clear_image (chooser);
918         }
919
920 out:
921         gtk_widget_destroy (widget);
922 }
923
924 static void
925 avatar_chooser_clicked_cb (GtkWidget            *button,
926                            EmpathyAvatarChooser *chooser)
927 {
928         GtkFileChooser *chooser_dialog;
929         GtkWidget      *image;
930         gchar          *saved_dir = NULL;
931         const gchar    *default_dir = DEFAULT_DIR;
932         const gchar    *pics_dir;
933         GtkFileFilter  *filter;
934
935         chooser_dialog = GTK_FILE_CHOOSER (
936                 gtk_file_chooser_dialog_new (_("Select Your Avatar Image"),
937                                              empathy_get_toplevel_window (GTK_WIDGET (chooser)),
938                                              GTK_FILE_CHOOSER_ACTION_OPEN,
939                                              _("No Image"),
940                                              GTK_RESPONSE_NO,
941                                              GTK_STOCK_CANCEL,
942                                              GTK_RESPONSE_CANCEL,
943                                              GTK_STOCK_OPEN,
944                                              GTK_RESPONSE_OK,
945                                              NULL));
946
947         /* Get special dirs */
948         empathy_conf_get_string (empathy_conf_get (),
949                                  EMPATHY_PREFS_UI_AVATAR_DIRECTORY,
950                                  &saved_dir);
951         if (saved_dir && !g_file_test (saved_dir, G_FILE_TEST_IS_DIR)) {
952                 g_free (saved_dir);
953                 saved_dir = NULL;
954         }
955         if (!g_file_test (default_dir, G_FILE_TEST_IS_DIR)) {
956                 default_dir = NULL;
957         }
958         pics_dir = g_get_user_special_dir (G_USER_DIRECTORY_PICTURES);
959         if (pics_dir && !g_file_test (pics_dir, G_FILE_TEST_IS_DIR)) {
960                 pics_dir = NULL;
961         }
962
963         /* Set current dir to the last one or to DEFAULT_DIR or to home */
964         if (saved_dir) {
965                 gtk_file_chooser_set_current_folder (chooser_dialog, saved_dir);
966         }
967         else if (pics_dir) {
968                 gtk_file_chooser_set_current_folder (chooser_dialog, pics_dir);
969         }
970         else if (default_dir) {
971                 gtk_file_chooser_set_current_folder (chooser_dialog, default_dir);
972         } else {
973                 gtk_file_chooser_set_current_folder (chooser_dialog, g_get_home_dir ());
974         }
975
976         /* Add shortcuts to special dirs */
977         if (saved_dir) {
978                 gtk_file_chooser_add_shortcut_folder (chooser_dialog, saved_dir, NULL);
979         }
980         else if (pics_dir) {
981                 gtk_file_chooser_add_shortcut_folder (chooser_dialog, pics_dir, NULL);
982         }
983         if (default_dir) {
984                 gtk_file_chooser_add_shortcut_folder (chooser_dialog, default_dir, NULL);
985         }
986
987         /* Setup preview image */
988         image = gtk_image_new ();
989         gtk_file_chooser_set_preview_widget (chooser_dialog, image);
990         gtk_widget_set_size_request (image, AVATAR_SIZE_SAVE, AVATAR_SIZE_SAVE);
991         gtk_widget_show (image);
992         gtk_file_chooser_set_use_preview_label (chooser_dialog, FALSE);
993         g_signal_connect (chooser_dialog, "update-preview",
994                           G_CALLBACK (avatar_chooser_update_preview_cb),
995                           chooser);
996
997         /* Setup filers */
998         filter = gtk_file_filter_new ();
999         gtk_file_filter_set_name (filter, _("Images"));
1000         gtk_file_filter_add_pixbuf_formats (filter);
1001         gtk_file_chooser_add_filter (chooser_dialog, filter);
1002         filter = gtk_file_filter_new ();
1003         gtk_file_filter_set_name (filter, _("All Files"));
1004         gtk_file_filter_add_pattern(filter, "*");
1005         gtk_file_chooser_add_filter (chooser_dialog, filter);
1006
1007         /* Setup response */
1008         gtk_dialog_set_default_response (GTK_DIALOG (chooser_dialog), GTK_RESPONSE_OK);
1009         g_signal_connect (chooser_dialog, "response",
1010                           G_CALLBACK (avatar_chooser_response_cb),
1011                           chooser);
1012
1013         gtk_widget_show (GTK_WIDGET (chooser_dialog));
1014         g_free (saved_dir);
1015 }
1016
1017 GtkWidget *
1018 empathy_avatar_chooser_new ()
1019 {
1020         return g_object_new (EMPATHY_TYPE_AVATAR_CHOOSER, NULL);
1021 }
1022
1023 void
1024 empathy_avatar_chooser_set (EmpathyAvatarChooser *chooser,
1025                             EmpathyAvatar        *avatar)
1026 {
1027         g_return_if_fail (EMPATHY_IS_AVATAR_CHOOSER (chooser));
1028
1029         if (avatar != NULL) {
1030                 avatar_chooser_set_image_from_avatar (chooser, avatar, FALSE);
1031         } else {
1032                 avatar_chooser_clear_image (chooser);
1033         }
1034 }
1035
1036 void
1037 empathy_avatar_chooser_get_image_data (EmpathyAvatarChooser  *chooser,
1038                                        const gchar          **data,
1039                                        gsize                 *data_size,
1040                                        const gchar          **mime_type)
1041 {
1042         EmpathyAvatarChooserPriv *priv;
1043
1044         g_return_if_fail (EMPATHY_IS_AVATAR_CHOOSER (chooser));
1045
1046         priv = GET_PRIV (chooser);
1047
1048         if (priv->avatar != NULL) {
1049                 if (data != NULL) {
1050                         *data = priv->avatar->data;
1051                 }
1052                 if (data_size != NULL) {
1053                         *data_size = priv->avatar->len;
1054                 }
1055                 if (mime_type != NULL) {
1056                         *mime_type = priv->avatar->format;
1057                 }
1058         } else {
1059                 if (data != NULL) {
1060                         *data = NULL;
1061                 }
1062                 if (data_size != NULL) {
1063                         *data_size = 0;
1064                 }
1065                 if (mime_type != NULL) {
1066                         *mime_type = NULL;
1067                 }
1068         }
1069 }
1070