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