]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-avatar-chooser.c
Make use of TP_CONNECTION_FEATURE_AVATAR_REQUIREMENTS
[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-utils.h>
33
34 #include "empathy-avatar-chooser.h"
35 #include "empathy-conf.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                    *converted_image_data = NULL;
415         gsize                     converted_image_size = 0;
416
417         req = tp_connection_get_avatar_requirements (priv->connection);
418         if (req == NULL) {
419                 DEBUG ("Avatar requirements not ready");
420                 return NULL;
421         }
422
423         /* Smaller is the factor, smaller will be the image.
424          * 0 is an empty image, 1 is the full size. */
425         min_factor = 0;
426         max_factor = 1;
427         factor = 1;
428
429         /* Check if we need to convert to another image format */
430         if (avatar_chooser_need_mime_type_conversion (avatar->format,
431                                                       req->supported_mime_types,
432                                                       &new_format_name,
433                                                       &new_mime_type)) {
434                 DEBUG ("Format conversion needed, we'll use mime type '%s' "
435                        "and format name '%s'. Current mime type is '%s'",
436                        new_mime_type, new_format_name, avatar->format);
437                 needs_conversion = TRUE;
438         }
439
440         /* If there is no format we can use, report error to the user. */
441         if (new_mime_type == NULL || new_format_name == NULL) {
442                 avatar_chooser_error_show (chooser, _("Couldn't convert image"),
443                                 _("None of the accepted image formats are "
444                                   "supported on your system"));
445                 return NULL;
446         }
447
448         /* If width or height are too big, it needs converting. */
449         width = gdk_pixbuf_get_width (pixbuf);
450         height = gdk_pixbuf_get_height (pixbuf);
451         if ((req->maximum_width > 0 && width > req->maximum_width) ||
452             (req->maximum_height > 0 && height > req->maximum_height)) {
453                 gdouble h_factor, v_factor;
454
455                 h_factor = (gdouble) req->maximum_width / width;
456                 v_factor = (gdouble) req->maximum_height / height;
457                 factor = max_factor = MIN (h_factor, v_factor);
458
459                 DEBUG ("Image dimensions (%dx%d) are too big. Max is %dx%d.",
460                        width, height, req->maximum_width, req->maximum_height);
461
462                 needs_conversion = TRUE;
463         }
464
465         /* If the data len is too big and no other conversion is needed,
466          * try with a lower factor. */
467         if (req->maximum_bytes > 0 && avatar->len > req->maximum_bytes && !needs_conversion) {
468                 DEBUG ("Image data (%"G_GSIZE_FORMAT" bytes) is too big "
469                        "(max is %u bytes), conversion needed.",
470                        avatar->len, req->maximum_bytes);
471
472                 factor = 0.5;
473                 needs_conversion = TRUE;
474         }
475
476         /* If no conversion is needed, return the avatar */
477         if (!needs_conversion) {
478                 g_free (new_format_name);
479                 g_free (new_mime_type);
480                 return empathy_avatar_ref (avatar);
481         }
482
483         do {
484                 GdkPixbuf *pixbuf_scaled = NULL;
485                 gboolean   saved;
486                 gint       new_width, new_height;
487                 GError    *error = NULL;
488
489                 g_free (converted_image_data);
490
491                 if (factor != 1) {
492                         new_width = width * factor;
493                         new_height = height * factor;
494                         pixbuf_scaled = gdk_pixbuf_scale_simple (pixbuf,
495                                                                  new_width,
496                                                                  new_height,
497                                                                  GDK_INTERP_HYPER);
498                 } else {
499                         new_width = width;
500                         new_height = height;
501                         pixbuf_scaled = g_object_ref (pixbuf);
502                 }
503
504                 DEBUG ("Trying with factor %f (%dx%d) and format %s...", factor,
505                         new_width, new_height, new_format_name);
506
507                 saved = gdk_pixbuf_save_to_buffer (pixbuf_scaled,
508                                                    &converted_image_data,
509                                                    &converted_image_size,
510                                                    new_format_name,
511                                                    &error, NULL);
512                 g_object_unref (pixbuf_scaled);
513
514                 if (!saved) {
515                         g_free (new_format_name);
516                         g_free (new_mime_type);
517                         avatar_chooser_error_show (chooser,
518                                 _("Couldn't convert image"),
519                                 error ? error->message : NULL);
520                         g_clear_error (&error);
521                         return NULL;
522                 }
523
524                 DEBUG ("Produced an image data of %"G_GSIZE_FORMAT" bytes.",
525                         converted_image_size);
526
527                 if (req->maximum_bytes == 0)
528                         break;
529
530                 /* Make a binary search for the bigest factor that produce
531                  * an image data size less than max_size */
532                 if (converted_image_size > req->maximum_bytes)
533                         max_factor = factor;
534                 if (converted_image_size < req->maximum_bytes)
535                         min_factor = factor;
536                 factor = (min_factor + max_factor)/2;
537
538                 /* We are done if either:
539                  * - min_factor == max_factor. That happens if we resized to
540                  *   the max required dimension and the produced data size is
541                  *   less than max_size.
542                  * - The data size is close enough to max_size. Here we accept
543                  *   a difference of 1k.
544                  */
545         } while (min_factor != max_factor &&
546                  abs (req->maximum_bytes - converted_image_size) > 1024);
547         g_free (new_format_name);
548
549         /* Takes ownership of new_mime_type and converted_image_data */
550         avatar = empathy_avatar_new ((guchar *) converted_image_data,
551                 converted_image_size, new_mime_type, NULL, NULL);
552
553         return avatar;
554 }
555
556 static void
557 avatar_chooser_clear_image (EmpathyAvatarChooser *chooser)
558 {
559         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
560         GtkWidget *image;
561
562         if (priv->avatar != NULL) {
563                 empathy_avatar_unref (priv->avatar);
564                 priv->avatar = NULL;
565         }
566
567         image = gtk_image_new_from_icon_name (EMPATHY_IMAGE_AVATAR_DEFAULT,
568                 GTK_ICON_SIZE_DIALOG);
569         gtk_button_set_image (GTK_BUTTON (chooser), image);
570         g_signal_emit (chooser, signals[CHANGED], 0);
571 }
572
573 static void
574 avatar_chooser_set_image_from_data (EmpathyAvatarChooser *chooser,
575                                     gchar                *data,
576                                     gsize                 size,
577                                     gboolean              set_locally)
578 {
579         GdkPixbuf     *pixbuf;
580         EmpathyAvatar *avatar = NULL;
581         gchar         *mime_type = NULL;
582
583         if (data == NULL) {
584                 avatar_chooser_clear_image (chooser);
585                 return;
586         }
587
588         pixbuf = empathy_pixbuf_from_data_and_mime (data, size, &mime_type);
589         if (pixbuf == NULL) {
590                 g_free (data);
591                 data = NULL;
592                 return;
593         }
594
595         /* avatar takes ownership of data and mime_type */
596         avatar = empathy_avatar_new ((guchar *) data, size, mime_type, NULL, NULL);
597
598         avatar_chooser_set_image (chooser, avatar, pixbuf, set_locally);
599 }
600
601 static void
602 avatar_chooser_set_image_from_avatar (EmpathyAvatarChooser *chooser,
603                                       EmpathyAvatar        *avatar,
604                                       gboolean              set_locally)
605 {
606         GdkPixbuf *pixbuf;
607         gchar     *mime_type = NULL;
608
609         g_assert (avatar != NULL);
610
611         pixbuf = empathy_pixbuf_from_data_and_mime ((gchar *) avatar->data,
612                                                     avatar->len,
613                                                     &mime_type);
614         if (pixbuf == NULL) {
615                 DEBUG ("couldn't make a pixbuf from avatar; giving up");
616                 return;
617         }
618
619         if (avatar->format == NULL) {
620                 avatar->format = mime_type;
621         } else {
622                 if (strcmp (mime_type, avatar->format)) {
623                         DEBUG ("avatar->format is %s; gdkpixbuf yields %s!",
624                                 avatar->format, mime_type);
625                 }
626                 g_free (mime_type);
627         }
628
629         empathy_avatar_ref (avatar);
630
631         avatar_chooser_set_image (chooser, avatar, pixbuf, set_locally);
632 }
633
634 static void
635 avatar_chooser_set_image (EmpathyAvatarChooser *chooser,
636                           EmpathyAvatar        *avatar,
637                           GdkPixbuf            *pixbuf,
638                           gboolean              set_locally)
639 {
640         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
641         GdkPixbuf                *pixbuf_view;
642         GtkWidget                *image;
643
644         g_assert (avatar != NULL);
645         g_assert (pixbuf != NULL);
646
647         if (set_locally) {
648                 EmpathyAvatar *conv;
649
650                 conv = avatar_chooser_maybe_convert_and_scale (chooser,
651                         pixbuf, avatar);
652                 empathy_avatar_unref (avatar);
653
654                 if (conv == NULL) {
655                         /* An error occured; don't change the avatar. */
656                         return;
657                 }
658
659                 avatar = conv;
660         }
661
662         if (priv->avatar != NULL) {
663                 empathy_avatar_unref (priv->avatar);
664         }
665         priv->avatar = avatar;
666
667         pixbuf_view = empathy_pixbuf_scale_down_if_necessary (pixbuf, AVATAR_SIZE_VIEW);
668         image = gtk_image_new_from_pixbuf (pixbuf_view);
669
670         gtk_button_set_image (GTK_BUTTON (chooser), image);
671         g_signal_emit (chooser, signals[CHANGED], 0);
672
673         g_object_unref (pixbuf_view);
674         g_object_unref (pixbuf);
675 }
676
677 static void
678 avatar_chooser_set_image_from_file (EmpathyAvatarChooser *chooser,
679                                     const gchar          *filename)
680 {
681         gchar  *image_data = NULL;
682         gsize   image_size = 0;
683         GError *error = NULL;
684
685         if (!g_file_get_contents (filename, &image_data, &image_size, &error)) {
686                 DEBUG ("Failed to load image from '%s': %s", filename,
687                         error ? error->message : "No error given");
688
689                 g_clear_error (&error);
690                 return;
691         }
692
693         avatar_chooser_set_image_from_data (chooser, image_data, image_size, TRUE);
694 }
695
696 static gboolean
697 avatar_chooser_drag_motion_cb (GtkWidget          *widget,
698                               GdkDragContext     *context,
699                               gint                x,
700                               gint                y,
701                               guint               time_,
702                               EmpathyAvatarChooser *chooser)
703 {
704         EmpathyAvatarChooserPriv *priv;
705         GList                  *p;
706
707         priv = GET_PRIV (chooser);
708
709         for (p = context->targets; p != NULL; p = p->next) {
710                 gchar *possible_type;
711
712                 possible_type = gdk_atom_name (GDK_POINTER_TO_ATOM (p->data));
713
714                 if (!strcmp (possible_type, URI_LIST_TYPE)) {
715                         g_free (possible_type);
716                         gdk_drag_status (context, GDK_ACTION_COPY, time_);
717
718                         return TRUE;
719                 }
720
721                 g_free (possible_type);
722         }
723
724         return FALSE;
725 }
726
727 static void
728 avatar_chooser_drag_leave_cb (GtkWidget          *widget,
729                              GdkDragContext     *context,
730                              guint               time_,
731                              EmpathyAvatarChooser *chooser)
732 {
733 }
734
735 static gboolean
736 avatar_chooser_drag_drop_cb (GtkWidget          *widget,
737                             GdkDragContext     *context,
738                             gint                x,
739                             gint                y,
740                             guint               time_,
741                             EmpathyAvatarChooser *chooser)
742 {
743         EmpathyAvatarChooserPriv *priv;
744         GList                  *p;
745
746         priv = GET_PRIV (chooser);
747
748         if (context->targets == NULL) {
749                 return FALSE;
750         }
751
752         for (p = context->targets; p != NULL; p = p->next) {
753                 char *possible_type;
754
755                 possible_type = gdk_atom_name (GDK_POINTER_TO_ATOM (p->data));
756                 if (!strcmp (possible_type, URI_LIST_TYPE)) {
757                         g_free (possible_type);
758                         gtk_drag_get_data (widget, context,
759                                            GDK_POINTER_TO_ATOM (p->data),
760                                            time_);
761
762                         return TRUE;
763                 }
764
765                 g_free (possible_type);
766         }
767
768         return FALSE;
769 }
770
771 static void
772 avatar_chooser_drag_data_received_cb (GtkWidget          *widget,
773                                      GdkDragContext     *context,
774                                      gint                x,
775                                      gint                y,
776                                      GtkSelectionData   *selection_data,
777                                      guint               info,
778                                      guint               time_,
779                                      EmpathyAvatarChooser *chooser)
780 {
781         gchar    *target_type;
782         gboolean  handled = FALSE;
783
784         target_type = gdk_atom_name (gtk_selection_data_get_target (selection_data));
785         if (!strcmp (target_type, URI_LIST_TYPE)) {
786                 GFile            *file;
787                 gchar            *nl;
788                 gchar            *data = NULL;
789                 gsize             bytes_read;
790
791                 nl = strstr ((gchar *) gtk_selection_data_get_data (selection_data),
792                                                 "\r\n");
793                 if (nl) {
794                         gchar *uri;
795
796                         uri = g_strndup ((gchar *) gtk_selection_data_get_data (selection_data),
797                                          nl - (gchar *) gtk_selection_data_get_data (selection_data));
798
799                         file = g_file_new_for_uri (uri);
800                         g_free (uri);
801                 } else {
802                         file = g_file_new_for_uri ((gchar *) gtk_selection_data_get_data (
803                                                 selection_data));
804                 }
805
806                 handled = g_file_load_contents (file, NULL, &data, &bytes_read,
807                                                 NULL, NULL);
808
809                 if (handled) {
810                         /* this in turn calls empathy_avatar_new (), which assumes
811                          * ownership of data.
812                          */
813                         avatar_chooser_set_image_from_data (chooser, data,
814                                                             bytes_read,
815                                                             TRUE);
816                 }
817
818                 g_object_unref (file);
819         }
820
821         gtk_drag_finish (context, handled, FALSE, time_);
822 }
823
824 static void
825 avatar_chooser_update_preview_cb (GtkFileChooser       *file_chooser,
826                                   EmpathyAvatarChooser *chooser)
827 {
828         gchar *filename;
829
830         filename = gtk_file_chooser_get_preview_filename (file_chooser);
831
832         if (filename) {
833                 GtkWidget *image;
834                 GdkPixbuf *pixbuf = NULL;
835                 GdkPixbuf *scaled_pixbuf;
836
837                 pixbuf = gdk_pixbuf_new_from_file (filename, NULL);
838
839                 image = gtk_file_chooser_get_preview_widget (file_chooser);
840
841                 if (pixbuf) {
842                         scaled_pixbuf = empathy_pixbuf_scale_down_if_necessary (pixbuf, AVATAR_SIZE_SAVE);
843                         gtk_image_set_from_pixbuf (GTK_IMAGE (image), scaled_pixbuf);
844                         g_object_unref (scaled_pixbuf);
845                         g_object_unref (pixbuf);
846                 } else {
847                         gtk_image_set_from_stock (GTK_IMAGE (image),
848                                                   "gtk-dialog-question",
849                                                   GTK_ICON_SIZE_DIALOG);
850                 }
851
852                 g_free (filename);
853         }
854
855         gtk_file_chooser_set_preview_widget_active (file_chooser, TRUE);
856 }
857
858 static void
859 avatar_chooser_response_cb (GtkWidget            *widget,
860                             gint                  response,
861                             EmpathyAvatarChooser *chooser)
862 {
863         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
864
865         priv->chooser_dialog = NULL;
866
867         if (response == GTK_RESPONSE_OK) {
868                 gchar *filename;
869                 gchar *path;
870
871                 filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (widget));
872                 avatar_chooser_set_image_from_file (chooser, filename);
873                 g_free (filename);
874
875                 path = gtk_file_chooser_get_current_folder (GTK_FILE_CHOOSER (widget));
876                 if (path) {
877                         empathy_conf_set_string (empathy_conf_get (),
878                                                  EMPATHY_PREFS_UI_AVATAR_DIRECTORY,
879                                                  path);
880                         g_free (path);
881                 }
882         }
883         else if (response == GTK_RESPONSE_NO) {
884                 /* This corresponds to "No Image", not to "Cancel" */
885                 avatar_chooser_clear_image (chooser);
886         }
887
888         gtk_widget_destroy (widget);
889 }
890
891 static void
892 avatar_chooser_clicked_cb (GtkWidget            *button,
893                            EmpathyAvatarChooser *chooser)
894 {
895         GtkFileChooser *chooser_dialog;
896         GtkWidget      *image;
897         gchar          *saved_dir = NULL;
898         const gchar    *default_dir = DEFAULT_DIR;
899         const gchar    *pics_dir;
900         GtkFileFilter  *filter;
901         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
902
903         if (priv->chooser_dialog) {
904                 gtk_window_present (GTK_WINDOW (priv->chooser_dialog));
905                 return;
906         }
907
908         priv->chooser_dialog = GTK_FILE_CHOOSER (
909                 gtk_file_chooser_dialog_new (_("Select Your Avatar Image"),
910                                              empathy_get_toplevel_window (GTK_WIDGET (chooser)),
911                                              GTK_FILE_CHOOSER_ACTION_OPEN,
912                                              _("No Image"),
913                                              GTK_RESPONSE_NO,
914                                              GTK_STOCK_CANCEL,
915                                              GTK_RESPONSE_CANCEL,
916                                              GTK_STOCK_OPEN,
917                                              GTK_RESPONSE_OK,
918                                              NULL));
919         chooser_dialog = priv->chooser_dialog;
920         gtk_window_set_destroy_with_parent (GTK_WINDOW (chooser_dialog), TRUE);
921
922         /* Get special dirs */
923         empathy_conf_get_string (empathy_conf_get (),
924                                  EMPATHY_PREFS_UI_AVATAR_DIRECTORY,
925                                  &saved_dir);
926         if (saved_dir && !g_file_test (saved_dir, G_FILE_TEST_IS_DIR)) {
927                 g_free (saved_dir);
928                 saved_dir = NULL;
929         }
930         if (!g_file_test (default_dir, G_FILE_TEST_IS_DIR)) {
931                 default_dir = NULL;
932         }
933         pics_dir = g_get_user_special_dir (G_USER_DIRECTORY_PICTURES);
934         if (pics_dir && !g_file_test (pics_dir, G_FILE_TEST_IS_DIR)) {
935                 pics_dir = NULL;
936         }
937
938         /* Set current dir to the last one or to DEFAULT_DIR or to home */
939         if (saved_dir) {
940                 gtk_file_chooser_set_current_folder (chooser_dialog, saved_dir);
941         }
942         else if (pics_dir) {
943                 gtk_file_chooser_set_current_folder (chooser_dialog, pics_dir);
944         }
945         else if (default_dir) {
946                 gtk_file_chooser_set_current_folder (chooser_dialog, default_dir);
947         } else {
948                 gtk_file_chooser_set_current_folder (chooser_dialog, g_get_home_dir ());
949         }
950
951         /* Add shortcuts to special dirs */
952         if (saved_dir) {
953                 gtk_file_chooser_add_shortcut_folder (chooser_dialog, saved_dir, NULL);
954         }
955         else if (pics_dir) {
956                 gtk_file_chooser_add_shortcut_folder (chooser_dialog, pics_dir, NULL);
957         }
958         if (default_dir) {
959                 gtk_file_chooser_add_shortcut_folder (chooser_dialog, default_dir, NULL);
960         }
961
962         /* Setup preview image */
963         image = gtk_image_new ();
964         gtk_file_chooser_set_preview_widget (chooser_dialog, image);
965         gtk_widget_set_size_request (image, AVATAR_SIZE_SAVE, AVATAR_SIZE_SAVE);
966         gtk_widget_show (image);
967         gtk_file_chooser_set_use_preview_label (chooser_dialog, FALSE);
968         g_signal_connect (chooser_dialog, "update-preview",
969                           G_CALLBACK (avatar_chooser_update_preview_cb),
970                           chooser);
971
972         /* Setup filers */
973         filter = gtk_file_filter_new ();
974         gtk_file_filter_set_name (filter, _("Images"));
975         gtk_file_filter_add_pixbuf_formats (filter);
976         gtk_file_chooser_add_filter (chooser_dialog, filter);
977         filter = gtk_file_filter_new ();
978         gtk_file_filter_set_name (filter, _("All Files"));
979         gtk_file_filter_add_pattern (filter, "*");
980         gtk_file_chooser_add_filter (chooser_dialog, filter);
981
982         /* Setup response */
983         gtk_dialog_set_default_response (GTK_DIALOG (chooser_dialog), GTK_RESPONSE_OK);
984         g_signal_connect (chooser_dialog, "response",
985                           G_CALLBACK (avatar_chooser_response_cb),
986                           chooser);
987
988         gtk_widget_show (GTK_WIDGET (chooser_dialog));
989         g_free (saved_dir);
990 }
991
992 /**
993  * empathy_avatar_chooser_new:
994  *
995  * Creates a new #EmpathyAvatarChooser.
996  *
997  * Return value: a new #EmpathyAvatarChooser
998  */
999 GtkWidget *
1000 empathy_avatar_chooser_new ()
1001 {
1002         return g_object_new (EMPATHY_TYPE_AVATAR_CHOOSER, NULL);
1003 }
1004
1005 /**
1006  * empathy_avatar_chooser_set:
1007  * @chooser: an #EmpathyAvatarChooser
1008  * @avatar: a new #EmpathyAvatar
1009  *
1010  * Sets the @chooser to display the avatar indicated by @avatar.
1011  */
1012 void
1013 empathy_avatar_chooser_set (EmpathyAvatarChooser *chooser,
1014                             EmpathyAvatar        *avatar)
1015 {
1016         g_return_if_fail (EMPATHY_IS_AVATAR_CHOOSER (chooser));
1017
1018         if (avatar != NULL) {
1019                 avatar_chooser_set_image_from_avatar (chooser, avatar, FALSE);
1020         } else {
1021                 avatar_chooser_clear_image (chooser);
1022         }
1023 }
1024
1025 /**
1026  * empathy_avatar_chooser_get_image_data:
1027  * @chooser: an #EmpathyAvatarChooser
1028  * @data: avatar bytes
1029  * @data_size: size of @data
1030  * @mime_type: avatar mime-type
1031  *
1032  * Gets image data about the currently selected avatar.
1033  */
1034 void
1035 empathy_avatar_chooser_get_image_data (EmpathyAvatarChooser  *chooser,
1036                                        const gchar          **data,
1037                                        gsize                 *data_size,
1038                                        const gchar          **mime_type)
1039 {
1040         EmpathyAvatarChooserPriv *priv;
1041
1042         g_return_if_fail (EMPATHY_IS_AVATAR_CHOOSER (chooser));
1043
1044         priv = GET_PRIV (chooser);
1045
1046         if (priv->avatar != NULL) {
1047                 if (data != NULL) {
1048                         *data = (gchar *) priv->avatar->data;
1049                 }
1050                 if (data_size != NULL) {
1051                         *data_size = priv->avatar->len;
1052                 }
1053                 if (mime_type != NULL) {
1054                         *mime_type = priv->avatar->format;
1055                 }
1056         } else {
1057                 if (data != NULL) {
1058                         *data = NULL;
1059                 }
1060                 if (data_size != NULL) {
1061                         *data_size = 0;
1062                 }
1063                 if (mime_type != NULL) {
1064                         *mime_type = NULL;
1065                 }
1066         }
1067 }
1068
1069 void
1070 empathy_avatar_chooser_set_account (EmpathyAvatarChooser *self,
1071                                        TpAccount *account)
1072 {
1073         g_return_if_fail (account != NULL);
1074
1075         avatar_chooser_set_connection (self, tp_account_get_connection (account));
1076         g_object_notify (G_OBJECT (self), "connection");
1077 }