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