]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-avatar-chooser.c
avatar-chooser: port to TP coding style
[empathy.git] / libempathy-gtk / empathy-avatar-chooser.c
1 /*
2  * Copyright (C) 2006-2007 Imendio AB.
3  * Copyright (C) 2007-2008 Collabora Ltd.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of version 2 of the GNU General Public
7  * License as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA  02110-1301  USA
18  *
19  * Authors: Based on Novell's e-image-chooser.
20  *          Xavier Claessens <xclaesse@gmail.com>
21  */
22
23 #include "config.h"
24
25 #include <string.h>
26
27 #include <glib/gi18n-lib.h>
28 #include <gtk/gtk.h>
29 #include <gio/gio.h>
30
31 #include <libempathy/empathy-gsettings.h>
32 #include <libempathy/empathy-utils.h>
33
34 #include "empathy-avatar-chooser.h"
35 #include "empathy-images.h"
36 #include "empathy-ui-utils.h"
37
38 #ifdef HAVE_CHEESE
39 #include <cheese-avatar-chooser.h>
40 #endif /* HAVE_CHEESE */
41
42
43 #define DEBUG_FLAG EMPATHY_DEBUG_OTHER
44 #include <libempathy/empathy-debug.h>
45
46 /**
47  * SECTION:empathy-avatar-chooser
48  * @title: EmpathyAvatarChooser
49  * @short_description: A widget used to change avatar
50  * @include: libempathy-gtk/empathy-avatar-chooser.h
51  *
52  * #EmpathyAvatarChooser is a widget which extends #GtkButton to
53  * provide a way of changing avatar.
54  */
55
56 /**
57  * EmpathyAvatarChooser:
58  * @parent: parent object
59  *
60  * Widget which extends #GtkButton to provide a way of changing avatar.
61  */
62
63 #define AVATAR_SIZE_SAVE 96
64 #define AVATAR_SIZE_VIEW 64
65 #define DEFAULT_DIR DATADIR"/pixmaps/faces"
66
67 #ifdef HAVE_CHEESE
68 /*
69  * A custom GtkResponseType used when the user presses the
70  * "Camera Picture" button. Any positive value would be sufficient.
71  */
72 #define EMPATHY_AVATAR_CHOOSER_RESPONSE_WEBCAM   10
73 #endif
74 #define EMPATHY_AVATAR_CHOOSER_RESPONSE_NO_IMAGE GTK_RESPONSE_NO
75 #define EMPATHY_AVATAR_CHOOSER_RESPONSE_CANCEL   GTK_RESPONSE_CANCEL
76 #define EMPATHY_AVATAR_CHOOSER_RESPONSE_FILE     GTK_RESPONSE_OK
77
78 struct _EmpathyAvatarChooserPrivate
79 {
80   TpConnection *connection;
81   GtkFileChooser *chooser_dialog;
82
83   gulong ready_handler_id;
84
85   EmpathyAvatar *avatar;
86   GSettings *gsettings_ui;
87 };
88
89 enum
90 {
91   CHANGED,
92   LAST_SIGNAL
93 };
94
95 enum
96 {
97   PROP_0,
98   PROP_CONNECTION
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 {
112   DND_TARGET_TYPE_URI_LIST
113 };
114
115 static const GtkTargetEntry drop_types[] =
116 {
117   { URI_LIST_TYPE, 0, DND_TARGET_TYPE_URI_LIST },
118 };
119
120 static void
121 avatar_chooser_get_property (GObject *object,
122     guint param_id,
123     GValue *value,
124     GParamSpec *pspec)
125 {
126   EmpathyAvatarChooser *self = (EmpathyAvatarChooser *) object;
127
128   switch (param_id)
129     {
130       case PROP_CONNECTION:
131         g_value_set_object (value, self->priv->connection);
132         break;
133       default:
134         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
135         break;
136     }
137 }
138
139 static void
140 avatar_chooser_set_connection (EmpathyAvatarChooser *self,
141     TpConnection *connection)
142 {
143   tp_clear_object (&self->priv->connection);
144
145   if (connection != NULL)
146     {
147       GQuark features[] = { TP_CONNECTION_FEATURE_AVATAR_REQUIREMENTS, 0 };
148       self->priv->connection = g_object_ref (connection);
149       tp_proxy_prepare_async (self->priv->connection, features, NULL, NULL);
150     }
151 }
152
153 static void
154 avatar_chooser_set_property (GObject *object,
155     guint param_id,
156     const GValue *value,
157     GParamSpec *pspec)
158 {
159   EmpathyAvatarChooser *self = EMPATHY_AVATAR_CHOOSER (object);
160
161   switch (param_id)
162     {
163       case PROP_CONNECTION:
164         avatar_chooser_set_connection (self, g_value_get_object (value));
165         break;
166       default:
167         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
168         break;
169     }
170 }
171
172 static void
173 avatar_chooser_finalize (GObject *object)
174 {
175   EmpathyAvatarChooser *self = (EmpathyAvatarChooser *) object;
176
177   avatar_chooser_set_connection (EMPATHY_AVATAR_CHOOSER (object), NULL);
178   g_assert (self->priv->connection == NULL);
179
180   tp_clear_pointer (&self->priv->avatar, empathy_avatar_unref);
181   tp_clear_object (&self->priv->gsettings_ui);
182
183   G_OBJECT_CLASS (empathy_avatar_chooser_parent_class)->finalize (object);
184 }
185
186 static void
187 empathy_avatar_chooser_class_init (EmpathyAvatarChooserClass *klass)
188 {
189   GObjectClass *object_class = G_OBJECT_CLASS (klass);
190   GParamSpec *param_spec;
191
192   object_class->finalize = avatar_chooser_finalize;
193   object_class->get_property = avatar_chooser_get_property;
194   object_class->set_property = avatar_chooser_set_property;
195
196   /**
197    * EmpathyAvatarChooser::changed:
198    * @self: an #EmpathyAvatarChooser
199    *
200    * Emitted when the chosen avatar has changed.
201    *
202    */
203   signals[CHANGED] =
204     g_signal_new ("changed",
205             G_TYPE_FROM_CLASS (klass),
206             G_SIGNAL_RUN_LAST,
207             0,
208             NULL, NULL,
209             g_cclosure_marshal_VOID__VOID,
210             G_TYPE_NONE, 0);
211
212   /**
213    * EmpathyAvatarChooser:connection:
214    *
215    * The #TpConnection whose avatar should be shown and modified by
216    * the #EmpathyAvatarChooser instance.
217    */
218   param_spec = g_param_spec_object ("connection",
219             "TpConnection",
220             "TpConnection whose avatar should be "
221             "shown and modified by this widget",
222             TP_TYPE_CONNECTION,
223             G_PARAM_READWRITE |
224             G_PARAM_STATIC_STRINGS);
225   g_object_class_install_property (object_class,
226            PROP_CONNECTION,
227            param_spec);
228
229   g_type_class_add_private (object_class, sizeof (EmpathyAvatarChooserPrivate));
230 }
231
232 static gboolean
233 avatar_chooser_drag_motion_cb (GtkWidget *widget,
234     GdkDragContext *context,
235     gint x,
236     gint y,
237     guint time_,
238     EmpathyAvatarChooser *self)
239 {
240   GList *p;
241
242   for (p = gdk_drag_context_list_targets (context); p != NULL;
243        p = p->next)
244     {
245       gchar *possible_type;
246
247       possible_type = gdk_atom_name (GDK_POINTER_TO_ATOM (p->data));
248
249       if (!strcmp (possible_type, URI_LIST_TYPE))
250         {
251           g_free (possible_type);
252           gdk_drag_status (context, GDK_ACTION_COPY, time_);
253
254           return TRUE;
255         }
256
257       g_free (possible_type);
258     }
259
260   return FALSE;
261 }
262
263 static void
264 avatar_chooser_drag_leave_cb (GtkWidget *widget,
265     GdkDragContext *context,
266     guint time_,
267     EmpathyAvatarChooser *self)
268 {
269 }
270
271 static gboolean
272 avatar_chooser_drag_drop_cb (GtkWidget *widget,
273     GdkDragContext *context,
274     gint x,
275     gint y,
276     guint time_,
277     EmpathyAvatarChooser *self)
278 {
279   GList *p;
280
281   if (gdk_drag_context_list_targets (context) == NULL)
282     return FALSE;
283
284   for (p = gdk_drag_context_list_targets (context);
285        p != NULL; p = p->next)
286     {
287       char *possible_type;
288
289       possible_type = gdk_atom_name (GDK_POINTER_TO_ATOM (p->data));
290       if (!strcmp (possible_type, URI_LIST_TYPE))
291         {
292           g_free (possible_type);
293           gtk_drag_get_data (widget, context,
294                  GDK_POINTER_TO_ATOM (p->data),
295                  time_);
296
297           return TRUE;
298         }
299
300       g_free (possible_type);
301     }
302
303   return FALSE;
304 }
305
306 static void
307 avatar_chooser_clear_image (EmpathyAvatarChooser *self)
308 {
309   GtkWidget *image;
310
311   tp_clear_pointer (&self->priv->avatar, empathy_avatar_unref);
312
313   image = gtk_image_new_from_icon_name (EMPATHY_IMAGE_AVATAR_DEFAULT,
314     GTK_ICON_SIZE_DIALOG);
315   gtk_button_set_image (GTK_BUTTON (self), image);
316   g_signal_emit (self, signals[CHANGED], 0);
317 }
318
319 static gboolean
320 str_in_strv (const gchar  *str,
321     gchar **strv)
322 {
323   if (strv == NULL)
324     return FALSE;
325
326   while (*strv != NULL)
327     {
328       if (g_str_equal (str, *strv))
329         return TRUE;
330
331       strv++;
332     }
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 avatar_chooser_need_mime_type_conversion (const gchar *current_mime_type,
342     gchar **accepted_mime_types,
343     gchar **satisfactory_format_name,
344     gchar **satisfactory_mime_type)
345 {
346   gchar *good_mime_types[] = {"image/jpeg", "image/png", NULL};
347   guint i;
348   GSList *formats, *l;
349   gboolean found = FALSE;
350
351   *satisfactory_format_name = NULL;
352   *satisfactory_mime_type = NULL;
353
354   /* If there is no accepted format there is nothing we can do */
355   if (accepted_mime_types == NULL || *accepted_mime_types == NULL)
356     return TRUE;
357
358   /* If the current mime type is good and accepted, don't change it!
359    * jpeg is compress better pictures, but png is better for logos and
360    * could have an alpha layer. */
361   if (str_in_strv (current_mime_type, good_mime_types) &&
362       str_in_strv (current_mime_type, accepted_mime_types))
363     {
364       *satisfactory_mime_type = g_strdup (current_mime_type);
365       *satisfactory_format_name = g_strdup (current_mime_type +
366                     strlen ("image/"));
367       return FALSE;
368     }
369
370   /* The current mime type is either not accepted or not good to use.
371    * Check if one of the good format is supported... */
372   for (i = 0; good_mime_types[i] != NULL;  i++)
373     {
374       if (str_in_strv (good_mime_types[i], accepted_mime_types))
375         {
376           *satisfactory_mime_type = g_strdup (good_mime_types[i]);
377           *satisfactory_format_name = g_strdup (good_mime_types[i] +
378               strlen ("image/"));
379           return TRUE;
380         }
381     }
382
383   /* Pick the first supported format we can write */
384   formats = gdk_pixbuf_get_formats ();
385   for (l = formats; !found && l != NULL; l = l->next)
386     {
387       GdkPixbufFormat *format = l->data;
388       gchar **format_mime_types;
389       gchar **iter;
390
391       if (!gdk_pixbuf_format_is_writable (format))
392         continue;
393
394       format_mime_types = gdk_pixbuf_format_get_mime_types (format);
395       for (iter = format_mime_types; *iter != NULL; iter++)
396         {
397           if (str_in_strv (*iter, accepted_mime_types))
398             {
399               *satisfactory_format_name = gdk_pixbuf_format_get_name (format);
400               *satisfactory_mime_type = g_strdup (*iter);
401               found = TRUE;
402               break;
403             }
404         }
405       g_strfreev (format_mime_types);
406     }
407   g_slist_free (formats);
408
409   return TRUE;
410 }
411
412 static void
413 avatar_chooser_error_show (EmpathyAvatarChooser *self,
414     const gchar *primary_text,
415     const gchar *secondary_text)
416 {
417   GtkWidget *parent;
418   GtkWidget *dialog;
419
420   parent = gtk_widget_get_toplevel (GTK_WIDGET (self));
421   if (!GTK_IS_WINDOW (parent))
422     parent = NULL;
423
424   dialog = gtk_message_dialog_new (parent ? GTK_WINDOW (parent) : NULL,
425       GTK_DIALOG_MODAL,
426       GTK_MESSAGE_WARNING,
427       GTK_BUTTONS_CLOSE,
428       "%s", primary_text);
429
430   if (secondary_text != NULL)
431     {
432       gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
433           "%s", secondary_text);
434     }
435
436   g_signal_connect (dialog, "response",
437         G_CALLBACK (gtk_widget_destroy), NULL);
438   gtk_widget_show (dialog);
439
440 }
441
442 static EmpathyAvatar *
443 avatar_chooser_maybe_convert_and_scale (EmpathyAvatarChooser *self,
444     GdkPixbuf *pixbuf,
445     EmpathyAvatar *avatar)
446 {
447   TpAvatarRequirements *req;
448   gboolean needs_conversion = FALSE;
449   guint width, height;
450   gchar *new_format_name = NULL;
451   gchar *new_mime_type = NULL;
452   gdouble min_factor, max_factor;
453   gdouble factor;
454   gchar *best_image_data = NULL;
455   gsize best_image_size = 0;
456   guint count = 0;
457
458   req = tp_connection_get_avatar_requirements (self->priv->connection);
459   if (req == NULL)
460     {
461       DEBUG ("Avatar requirements not ready");
462       return NULL;
463     }
464
465   /* Smaller is the factor, smaller will be the image.
466    * 0 is an empty image, 1 is the full size. */
467   min_factor = 0;
468   max_factor = 1;
469   factor = 1;
470
471   /* Check if we need to convert to another image format */
472   if (avatar_chooser_need_mime_type_conversion (avatar->format,
473         req->supported_mime_types, &new_format_name, &new_mime_type))
474     {
475       DEBUG ("Format conversion needed, we'll use mime type '%s' "
476              "and format name '%s'. Current mime type is '%s'",
477              new_mime_type, new_format_name, avatar->format);
478       needs_conversion = TRUE;
479     }
480
481   /* If there is no format we can use, report error to the user. */
482   if (new_mime_type == NULL || new_format_name == NULL)
483     {
484       avatar_chooser_error_show (self, _("Couldn't convert image"),
485           _("None of the accepted image formats are "
486             "supported on your system"));
487       return NULL;
488     }
489
490   /* If width or height are too big, it needs converting. */
491   width = gdk_pixbuf_get_width (pixbuf);
492   height = gdk_pixbuf_get_height (pixbuf);
493   if ((req->maximum_width > 0 && width > req->maximum_width) ||
494       (req->maximum_height > 0 && height > req->maximum_height))
495     {
496       gdouble h_factor, v_factor;
497
498       h_factor = (gdouble) req->maximum_width / width;
499       v_factor = (gdouble) req->maximum_height / height;
500       factor = max_factor = MIN (h_factor, v_factor);
501
502       DEBUG ("Image dimensions (%dx%d) are too big. Max is %dx%d.",
503           width, height, req->maximum_width, req->maximum_height);
504
505       needs_conversion = TRUE;
506     }
507
508   /* If the data len is too big and no other conversion is needed,
509    * try with a lower factor. */
510   if (req->maximum_bytes > 0 && avatar->len > req->maximum_bytes &&
511       !needs_conversion)
512     {
513       DEBUG ("Image data (%"G_GSIZE_FORMAT" bytes) is too big "
514              "(max is %u bytes), conversion needed.",
515              avatar->len, req->maximum_bytes);
516
517       factor = 0.5;
518       needs_conversion = TRUE;
519     }
520
521   /* If no conversion is needed, return the avatar */
522   if (!needs_conversion)
523     {
524       g_free (new_format_name);
525       g_free (new_mime_type);
526       return empathy_avatar_ref (avatar);
527     }
528
529   do
530     {
531       GdkPixbuf *pixbuf_scaled = NULL;
532       gboolean saved;
533       gint new_width, new_height;
534       gchar *converted_image_data;
535       gsize converted_image_size;
536       GError *error = NULL;
537
538       if (factor != 1)
539         {
540           new_width = width * factor;
541           new_height = height * factor;
542           pixbuf_scaled = gdk_pixbuf_scale_simple (pixbuf,
543                      new_width,
544                      new_height,
545                      GDK_INTERP_HYPER);
546         }
547       else
548         {
549           new_width = width;
550           new_height = height;
551           pixbuf_scaled = g_object_ref (pixbuf);
552         }
553
554       DEBUG ("Trying with factor %f (%dx%d) and format %s...", factor,
555         new_width, new_height, new_format_name);
556
557       saved = gdk_pixbuf_save_to_buffer (pixbuf_scaled,
558           &converted_image_data,
559           &converted_image_size,
560           new_format_name,
561           &error, NULL);
562       g_object_unref (pixbuf_scaled);
563
564       if (!saved)
565         {
566           g_free (new_format_name);
567           g_free (new_mime_type);
568           avatar_chooser_error_show (self,
569             _("Couldn't convert image"),
570             error ? error->message : NULL);
571           g_clear_error (&error);
572           return NULL;
573         }
574
575       DEBUG ("Produced an image data of %"G_GSIZE_FORMAT" bytes.",
576         converted_image_size);
577
578       /* If the new image satisfy the req, keep it as current best */
579       if (req->maximum_bytes == 0 || converted_image_size <= req->maximum_bytes)
580         {
581           g_free (best_image_data);
582
583           best_image_data = converted_image_data;
584           best_image_size = converted_image_size;
585
586           /* If this image is close enough to the optimal size,
587            * stop searching */
588           if (req->maximum_bytes == 0 ||
589               req->maximum_bytes - converted_image_size <= 1024)
590             break;
591         }
592       else
593         {
594           g_free (converted_image_data);
595         }
596
597     /* Make a binary search for the bigest factor that produce
598      * an image data size less than max_size */
599     if (converted_image_size > req->maximum_bytes)
600       max_factor = factor;
601     if (converted_image_size < req->maximum_bytes)
602       min_factor = factor;
603     factor = (min_factor + max_factor)/2;
604
605     if ((int) (width * factor) == new_width ||
606         (int) (height * factor) == new_height)
607       {
608         /* min_factor and max_factor are too close, so the new
609          * factor will produce the same image as previous
610          * iteration. No need to continue, we already found
611          * the optimal size. */
612         break;
613       }
614
615     /* Do 10 iterations in the worst case */
616   } while (++count < 10);
617
618   g_free (new_format_name);
619
620   /* Takes ownership of new_mime_type and best_image_data */
621   avatar = empathy_avatar_new ((guchar *) best_image_data,
622     best_image_size, new_mime_type, NULL);
623
624   return avatar;
625 }
626
627 static void
628 avatar_chooser_set_image (EmpathyAvatarChooser *self,
629     EmpathyAvatar *avatar,
630     GdkPixbuf *pixbuf,
631     gboolean set_locally)
632 {
633   GdkPixbuf *pixbuf_view;
634   GtkWidget *image;
635
636   g_assert (avatar != NULL);
637   g_assert (pixbuf != NULL);
638
639   if (set_locally)
640     {
641       EmpathyAvatar *conv;
642
643       conv = avatar_chooser_maybe_convert_and_scale (self,
644         pixbuf, avatar);
645       empathy_avatar_unref (avatar);
646
647       if (conv == NULL)
648         /* An error occured; don't change the avatar. */
649         return;
650
651       avatar = conv;
652     }
653
654   tp_clear_pointer (&self->priv->avatar, empathy_avatar_unref);
655   self->priv->avatar = avatar;
656
657   pixbuf_view = empathy_pixbuf_scale_down_if_necessary (pixbuf,
658       AVATAR_SIZE_VIEW);
659   image = gtk_image_new_from_pixbuf (pixbuf_view);
660
661   gtk_button_set_image (GTK_BUTTON (self), image);
662   g_signal_emit (self, signals[CHANGED], 0);
663
664   g_object_unref (pixbuf_view);
665   g_object_unref (pixbuf);
666 }
667
668 static void
669 avatar_chooser_set_image_from_data (EmpathyAvatarChooser *self,
670     gchar *data,
671     gsize size,
672     gboolean set_locally)
673 {
674   GdkPixbuf *pixbuf;
675   EmpathyAvatar *avatar = NULL;
676   gchar *mime_type = NULL;
677
678   if (data == NULL)
679     {
680       avatar_chooser_clear_image (self);
681       return;
682     }
683
684   pixbuf = empathy_pixbuf_from_data_and_mime (data, size, &mime_type);
685   if (pixbuf == NULL)
686     {
687       g_free (data);
688       data = NULL;
689       return;
690     }
691
692   /* avatar takes ownership of data and mime_type */
693   avatar = empathy_avatar_new ((guchar *) data, size, mime_type, NULL);
694
695   avatar_chooser_set_image (self, avatar, pixbuf, set_locally);
696 }
697
698 static void
699 avatar_chooser_drag_data_received_cb (GtkWidget          *widget,
700     GdkDragContext *context,
701     gint x,
702     gint y,
703     GtkSelectionData *selection_data,
704     guint info,
705     guint time_,
706     EmpathyAvatarChooser *self)
707 {
708   gchar *target_type;
709   gboolean handled = FALSE;
710
711   target_type = gdk_atom_name (gtk_selection_data_get_target (selection_data));
712   if (!strcmp (target_type, URI_LIST_TYPE))
713     {
714       GFile *file;
715       gchar *nl;
716       gchar *data = NULL;
717       gsize bytes_read;
718
719       nl = strstr ((gchar *) gtk_selection_data_get_data (selection_data),
720               "\r\n");
721       if (nl != NULL)
722         {
723           gchar *uri;
724
725           uri = g_strndup (
726               (gchar *) gtk_selection_data_get_data (selection_data),
727               nl - (gchar *) gtk_selection_data_get_data (selection_data));
728
729           file = g_file_new_for_uri (uri);
730           g_free (uri);
731         }
732       else
733         {
734           file = g_file_new_for_uri ((gchar *) gtk_selection_data_get_data (
735                 selection_data));
736         }
737
738       handled = g_file_load_contents (file, NULL, &data, &bytes_read,
739               NULL, NULL);
740
741       if (handled)
742         {
743           /* this in turn calls empathy_avatar_new (), which assumes
744            * ownership of data.
745            */
746           avatar_chooser_set_image_from_data (self, data,
747                       bytes_read,
748                       TRUE);
749         }
750
751       g_object_unref (file);
752     }
753
754   gtk_drag_finish (context, handled, FALSE, time_);
755 }
756
757 static void
758 avatar_chooser_update_preview_cb (GtkFileChooser *file_chooser,
759     EmpathyAvatarChooser *self)
760 {
761   gchar *filename;
762
763   filename = gtk_file_chooser_get_preview_filename (file_chooser);
764
765   if (filename != NULL)
766     {
767       GtkWidget *image;
768       GdkPixbuf *pixbuf = NULL;
769       GdkPixbuf *scaled_pixbuf;
770
771       pixbuf = gdk_pixbuf_new_from_file (filename, NULL);
772
773       image = gtk_file_chooser_get_preview_widget (file_chooser);
774
775       if (pixbuf != NULL)
776         {
777           scaled_pixbuf = empathy_pixbuf_scale_down_if_necessary (pixbuf,
778               AVATAR_SIZE_SAVE);
779
780           gtk_image_set_from_pixbuf (GTK_IMAGE (image), scaled_pixbuf);
781           g_object_unref (scaled_pixbuf);
782           g_object_unref (pixbuf);
783         }
784       else
785         {
786           gtk_image_set_from_stock (GTK_IMAGE (image),
787                   "gtk-dialog-question",
788                   GTK_ICON_SIZE_DIALOG);
789         }
790
791       g_free (filename);
792     }
793
794   gtk_file_chooser_set_preview_widget_active (file_chooser, TRUE);
795 }
796
797 static void
798 avatar_chooser_set_image_from_file (EmpathyAvatarChooser *self,
799     const gchar *filename)
800 {
801   gchar *image_data = NULL;
802   gsize  image_size = 0;
803   GError *error = NULL;
804
805   if (!g_file_get_contents (filename, &image_data, &image_size, &error))
806     {
807       DEBUG ("Failed to load image from '%s': %s", filename,
808         error ? error->message : "No error given");
809
810       g_clear_error (&error);
811       return;
812     }
813
814   avatar_chooser_set_image_from_data (self, image_data, image_size, TRUE);
815 }
816
817 #ifdef HAVE_CHEESE
818 static void
819 avatar_chooser_set_avatar_from_pixbuf (EmpathyAvatarChooser *self,
820                GdkPixbuf *pb)
821 {
822   /* dup the string as empathy_avatar_new steals ownership of the it */
823   gchar *mime = g_strdup ("image/png");
824   gsize size;
825   gchar *buf;
826   EmpathyAvatar *avatar = NULL;
827   GError *error = NULL;
828
829   if (!gdk_pixbuf_save_to_buffer (pb, &buf, &size, "png", &error, NULL))
830     {
831       avatar_chooser_error_show (self,
832         _("Couldn't save pixbuf to png"),
833         error ? error->message : NULL);
834       g_clear_error (&error);
835       return;
836     }
837
838   avatar = empathy_avatar_new ((guchar *) buf, size, mime, NULL);
839   avatar_chooser_set_image (self, avatar, pb, TRUE);
840 }
841
842 static gboolean
843 destroy_chooser (GtkWidget *self)
844 {
845   gtk_widget_destroy (self);
846   return FALSE;
847 }
848
849 static void
850 webcam_response_cb (GtkDialog *dialog,
851         int response,
852         EmpathyAvatarChooser *self)
853 {
854   if (response == GTK_RESPONSE_ACCEPT)
855     {
856       GdkPixbuf *pb;
857       CheeseAvatarChooser *cheese_chooser;
858
859       cheese_chooser = CHEESE_AVATAR_CHOOSER (dialog);
860       pb = cheese_avatar_chooser_get_picture (cheese_chooser);
861       avatar_chooser_set_avatar_from_pixbuf (self, pb);
862     }
863
864   if (response != GTK_RESPONSE_DELETE_EVENT &&
865       response != GTK_RESPONSE_NONE)
866     g_idle_add ((GSourceFunc) destroy_chooser, dialog);
867 }
868
869 static void
870 choose_avatar_from_webcam (GtkWidget *widget,
871     EmpathyAvatarChooser *self)
872 {
873   GtkWidget *window;
874
875   window = cheese_avatar_chooser_new ();
876
877   gtk_window_set_transient_for (GTK_WINDOW (window),
878       GTK_WINDOW (empathy_get_toplevel_window (GTK_WIDGET (self))));
879   gtk_window_set_modal (GTK_WINDOW (window), TRUE);
880   g_signal_connect (G_OBJECT (window), "response",
881       G_CALLBACK (webcam_response_cb), self);
882   gtk_widget_show (window);
883 }
884 #endif /* HAVE_CHEESE */
885
886 static void
887 avatar_chooser_response_cb (GtkWidget *widget,
888     gint response,
889     EmpathyAvatarChooser *self)
890 {
891   self->priv->chooser_dialog = NULL;
892
893   if (response == EMPATHY_AVATAR_CHOOSER_RESPONSE_FILE)
894     {
895       gchar *filename;
896       gchar *path;
897
898       filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (widget));
899       avatar_chooser_set_image_from_file (self, filename);
900       g_free (filename);
901
902       path = gtk_file_chooser_get_current_folder (GTK_FILE_CHOOSER (widget));
903       if (path != NULL)
904         {
905           g_settings_set_string (self->priv->gsettings_ui,
906                      EMPATHY_PREFS_UI_AVATAR_DIRECTORY,
907                      path);
908
909           g_free (path);
910         }
911     }
912   else if (response == EMPATHY_AVATAR_CHOOSER_RESPONSE_NO_IMAGE)
913     {
914       /* This corresponds to "No Image", not to "Cancel" */
915       avatar_chooser_clear_image (self);
916     }
917   #ifdef HAVE_CHEESE
918   else if (response == EMPATHY_AVATAR_CHOOSER_RESPONSE_WEBCAM)
919     {
920       /* This corresponds to "Camera Picture" */
921       choose_avatar_from_webcam (widget, self);
922     }
923   #endif
924
925   gtk_widget_destroy (widget);
926 }
927
928 static void
929 avatar_chooser_clicked_cb (GtkWidget *button,
930     EmpathyAvatarChooser *self)
931 {
932   GtkFileChooser *chooser_dialog;
933   GtkWidget *image;
934   gchar *saved_dir = NULL;
935   const gchar *default_dir = DEFAULT_DIR;
936   const gchar *pics_dir;
937   GtkFileFilter *filter;
938
939   if (self->priv->chooser_dialog != NULL)
940     {
941       gtk_window_present (GTK_WINDOW (self->priv->chooser_dialog));
942       return;
943     }
944
945   self->priv->chooser_dialog = GTK_FILE_CHOOSER (
946       gtk_file_chooser_dialog_new (_("Select Your Avatar Image"),
947         empathy_get_toplevel_window (GTK_WIDGET (self)),
948         GTK_FILE_CHOOSER_ACTION_OPEN,
949         #ifdef HAVE_CHEESE
950         _("Take a picture..."),
951         EMPATHY_AVATAR_CHOOSER_RESPONSE_WEBCAM,
952         #endif
953         _("No Image"),
954         EMPATHY_AVATAR_CHOOSER_RESPONSE_NO_IMAGE,
955         GTK_STOCK_CANCEL,
956         EMPATHY_AVATAR_CHOOSER_RESPONSE_CANCEL,
957         GTK_STOCK_OPEN,
958         EMPATHY_AVATAR_CHOOSER_RESPONSE_FILE,
959         NULL));
960
961   chooser_dialog = self->priv->chooser_dialog;
962   gtk_window_set_destroy_with_parent (GTK_WINDOW (chooser_dialog), TRUE);
963
964   /* Get special dirs */
965   saved_dir = g_settings_get_string (self->priv->gsettings_ui,
966              EMPATHY_PREFS_UI_AVATAR_DIRECTORY);
967
968   if (saved_dir != NULL &&
969       !g_file_test (saved_dir, G_FILE_TEST_IS_DIR))
970     {
971       g_free (saved_dir);
972       saved_dir = NULL;
973     }
974
975   if (!g_file_test (default_dir, G_FILE_TEST_IS_DIR))
976     default_dir = NULL;
977
978   pics_dir = g_get_user_special_dir (G_USER_DIRECTORY_PICTURES);
979   if (pics_dir != NULL && !g_file_test (pics_dir, G_FILE_TEST_IS_DIR))
980     pics_dir = NULL;
981
982   /* Set current dir to the last one or to DEFAULT_DIR or to home */
983   if (saved_dir != NULL)
984     gtk_file_chooser_set_current_folder (chooser_dialog, saved_dir);
985   else if (pics_dir != NULL)
986     gtk_file_chooser_set_current_folder (chooser_dialog, pics_dir);
987   else if (default_dir != NULL)
988     gtk_file_chooser_set_current_folder (chooser_dialog, default_dir);
989   else
990     gtk_file_chooser_set_current_folder (chooser_dialog, g_get_home_dir ());
991
992   /* Add shortcuts to special dirs */
993   if (saved_dir)
994     gtk_file_chooser_add_shortcut_folder (chooser_dialog, saved_dir, NULL);
995   else if (pics_dir)
996     gtk_file_chooser_add_shortcut_folder (chooser_dialog, pics_dir, NULL);
997
998   if (default_dir != NULL)
999     gtk_file_chooser_add_shortcut_folder (chooser_dialog, default_dir, NULL);
1000
1001   /* Setup preview image */
1002   image = gtk_image_new ();
1003   gtk_file_chooser_set_preview_widget (chooser_dialog, image);
1004   gtk_widget_set_size_request (image, AVATAR_SIZE_SAVE, AVATAR_SIZE_SAVE);
1005   gtk_widget_show (image);
1006   gtk_file_chooser_set_use_preview_label (chooser_dialog, FALSE);
1007   g_signal_connect (chooser_dialog, "update-preview",
1008       G_CALLBACK (avatar_chooser_update_preview_cb),
1009       self);
1010
1011   /* Setup filers */
1012   filter = gtk_file_filter_new ();
1013   gtk_file_filter_set_name (filter, _("Images"));
1014   gtk_file_filter_add_pixbuf_formats (filter);
1015   gtk_file_chooser_add_filter (chooser_dialog, filter);
1016   filter = gtk_file_filter_new ();
1017   gtk_file_filter_set_name (filter, _("All Files"));
1018   gtk_file_filter_add_pattern (filter, "*");
1019   gtk_file_chooser_add_filter (chooser_dialog, filter);
1020
1021   /* Setup response */
1022   gtk_dialog_set_default_response (GTK_DIALOG (chooser_dialog),
1023       EMPATHY_AVATAR_CHOOSER_RESPONSE_FILE);
1024
1025   g_signal_connect (chooser_dialog, "response",
1026       G_CALLBACK (avatar_chooser_response_cb),
1027       self);
1028
1029   gtk_widget_show (GTK_WIDGET (chooser_dialog));
1030
1031   g_free (saved_dir);
1032 }
1033
1034 static void
1035 empathy_avatar_chooser_init (EmpathyAvatarChooser *self)
1036 {
1037   self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self,
1038     EMPATHY_TYPE_AVATAR_CHOOSER, EmpathyAvatarChooserPrivate);
1039
1040   gtk_drag_dest_set (GTK_WIDGET (self),
1041       GTK_DEST_DEFAULT_ALL,
1042       drop_types,
1043       G_N_ELEMENTS (drop_types),
1044       GDK_ACTION_COPY);
1045
1046   self->priv->gsettings_ui = g_settings_new (EMPATHY_PREFS_UI_SCHEMA);
1047
1048   g_signal_connect (self, "drag-motion",
1049       G_CALLBACK (avatar_chooser_drag_motion_cb),
1050       self);
1051   g_signal_connect (self, "drag-leave",
1052       G_CALLBACK (avatar_chooser_drag_leave_cb),
1053       self);
1054   g_signal_connect (self, "drag-drop",
1055       G_CALLBACK (avatar_chooser_drag_drop_cb),
1056       self);
1057   g_signal_connect (self, "drag-data-received",
1058       G_CALLBACK (avatar_chooser_drag_data_received_cb),
1059       self);
1060   g_signal_connect (self, "clicked",
1061       G_CALLBACK (avatar_chooser_clicked_cb),
1062       self);
1063
1064   empathy_avatar_chooser_set (self, NULL);
1065 }
1066
1067 static void
1068 avatar_chooser_set_image_from_avatar (EmpathyAvatarChooser *self,
1069     EmpathyAvatar *avatar,
1070     gboolean set_locally)
1071 {
1072   GdkPixbuf *pixbuf;
1073   gchar *mime_type = NULL;
1074
1075   g_assert (avatar != NULL);
1076
1077   pixbuf = empathy_pixbuf_from_data_and_mime ((gchar *) avatar->data,
1078       avatar->len, &mime_type);
1079
1080   if (pixbuf == NULL)
1081     {
1082       DEBUG ("couldn't make a pixbuf from avatar; giving up");
1083       return;
1084     }
1085
1086   if (avatar->format == NULL)
1087     {
1088       avatar->format = mime_type;
1089     }
1090   else
1091     {
1092       if (strcmp (mime_type, avatar->format))
1093         DEBUG ("avatar->format is %s; gdkpixbuf yields %s!",
1094           avatar->format, mime_type);
1095
1096       g_free (mime_type);
1097     }
1098
1099   empathy_avatar_ref (avatar);
1100
1101   avatar_chooser_set_image (self, avatar, pixbuf, set_locally);
1102 }
1103
1104 /**
1105  * empathy_avatar_chooser_new:
1106  *
1107  * Creates a new #EmpathyAvatarChooser.
1108  *
1109  * Return value: a new #EmpathyAvatarChooser
1110  */
1111 GtkWidget *
1112 empathy_avatar_chooser_new (void)
1113 {
1114   return g_object_new (EMPATHY_TYPE_AVATAR_CHOOSER, NULL);
1115 }
1116
1117 /**
1118  * empathy_avatar_chooser_set:
1119  * @self: an #EmpathyAvatarChooser
1120  * @avatar: a new #EmpathyAvatar
1121  *
1122  * Sets the @self to display the avatar indicated by @avatar.
1123  */
1124 void
1125 empathy_avatar_chooser_set (EmpathyAvatarChooser *self,
1126     EmpathyAvatar *avatar)
1127 {
1128   g_return_if_fail (EMPATHY_IS_AVATAR_CHOOSER (self));
1129
1130   if (avatar != NULL)
1131     avatar_chooser_set_image_from_avatar (self, avatar, FALSE);
1132   else
1133     avatar_chooser_clear_image (self);
1134 }
1135
1136 /**
1137  * empathy_avatar_chooser_get_image_data:
1138  * @self: an #EmpathyAvatarChooser
1139  * @data: avatar bytes
1140  * @data_size: size of @data
1141  * @mime_type: avatar mime-type
1142  *
1143  * Gets image data about the currently selected avatar.
1144  */
1145 void
1146 empathy_avatar_chooser_get_image_data (EmpathyAvatarChooser  *self,
1147     const gchar **data,
1148     gsize *data_size,
1149     const gchar **mime_type)
1150 {
1151   g_return_if_fail (EMPATHY_IS_AVATAR_CHOOSER (self));
1152
1153   if (self->priv->avatar != NULL)
1154     {
1155       if (data != NULL)
1156         *data = (gchar *) self->priv->avatar->data;
1157
1158       if (data_size != NULL)
1159         *data_size = self->priv->avatar->len;
1160
1161       if (mime_type != NULL)
1162         *mime_type = self->priv->avatar->format;
1163   }
1164   else
1165     {
1166       if (data != NULL)
1167         *data = NULL;
1168
1169       if (data_size != NULL)
1170         *data_size = 0;
1171
1172       if (mime_type != NULL)
1173         *mime_type = NULL;
1174     }
1175 }
1176
1177 void
1178 empathy_avatar_chooser_set_account (EmpathyAvatarChooser *self,
1179     TpAccount *account)
1180 {
1181   g_return_if_fail (account != NULL);
1182
1183   avatar_chooser_set_connection (self, tp_account_get_connection (account));
1184   g_object_notify (G_OBJECT (self), "connection");
1185 }