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