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