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