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