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