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