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