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