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