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