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