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