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