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