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