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