]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-avatar-chooser.c
Merge branch 'sasl'
[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-gsettings.h>
33 #include <libempathy/empathy-utils.h>
34
35 #include "empathy-avatar-chooser.h"
36 #include "empathy-images.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         TpConnection            *connection;
66         GtkFileChooser          *chooser_dialog;
67
68         gulong ready_handler_id;
69
70         EmpathyAvatar *avatar;
71         GSettings *gsettings_ui;
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         priv->gsettings_ui = g_settings_new (EMPATHY_PREFS_UI_SCHEMA);
231
232         g_signal_connect (chooser, "drag-motion",
233                           G_CALLBACK (avatar_chooser_drag_motion_cb),
234                           chooser);
235         g_signal_connect (chooser, "drag-leave",
236                           G_CALLBACK (avatar_chooser_drag_leave_cb),
237                           chooser);
238         g_signal_connect (chooser, "drag-drop",
239                           G_CALLBACK (avatar_chooser_drag_drop_cb),
240                           chooser);
241         g_signal_connect (chooser, "drag-data-received",
242                           G_CALLBACK (avatar_chooser_drag_data_received_cb),
243                           chooser);
244         g_signal_connect (chooser, "clicked",
245                           G_CALLBACK (avatar_chooser_clicked_cb),
246                           chooser);
247
248         empathy_avatar_chooser_set (chooser, NULL);
249 }
250
251 static void
252 avatar_chooser_finalize (GObject *object)
253 {
254         EmpathyAvatarChooserPriv *priv;
255
256         priv = GET_PRIV (object);
257
258         avatar_chooser_set_connection (EMPATHY_AVATAR_CHOOSER (object), NULL);
259         g_assert (priv->connection == NULL);
260
261         if (priv->avatar != NULL) {
262                 empathy_avatar_unref (priv->avatar);
263         }
264
265         g_object_unref (priv->gsettings_ui);
266
267         G_OBJECT_CLASS (empathy_avatar_chooser_parent_class)->finalize (object);
268 }
269
270 static void
271 avatar_chooser_set_connection (EmpathyAvatarChooser *self,
272                                TpConnection         *connection)
273 {
274         EmpathyAvatarChooserPriv *priv = GET_PRIV (self);
275
276         if (priv->connection != NULL) {
277                 g_object_unref (priv->connection);
278                 priv->connection = NULL;
279         }
280
281         if (connection != NULL) {
282                 GQuark features[] = { TP_CONNECTION_FEATURE_AVATAR_REQUIREMENTS, 0 };
283                 priv->connection = g_object_ref (connection);
284                 tp_proxy_prepare_async (priv->connection, features, NULL, NULL);
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         TpAvatarRequirements     *req;
413         gboolean                  needs_conversion = FALSE;
414         guint                     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                    *best_image_data = NULL;
420         gsize                     best_image_size = 0;
421         guint                     count = 0;
422
423         req = tp_connection_get_avatar_requirements (priv->connection);
424         if (req == NULL) {
425                 DEBUG ("Avatar requirements not ready");
426                 return NULL;
427         }
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                                                       req->supported_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
446         /* If there is no format we can use, report error to the user. */
447         if (new_mime_type == NULL || new_format_name == NULL) {
448                 avatar_chooser_error_show (chooser, _("Couldn't convert image"),
449                                 _("None of the accepted image formats are "
450                                   "supported on your system"));
451                 return NULL;
452         }
453
454         /* If width or height are too big, it needs converting. */
455         width = gdk_pixbuf_get_width (pixbuf);
456         height = gdk_pixbuf_get_height (pixbuf);
457         if ((req->maximum_width > 0 && width > req->maximum_width) ||
458             (req->maximum_height > 0 && height > req->maximum_height)) {
459                 gdouble h_factor, v_factor;
460
461                 h_factor = (gdouble) req->maximum_width / width;
462                 v_factor = (gdouble) req->maximum_height / height;
463                 factor = max_factor = MIN (h_factor, v_factor);
464
465                 DEBUG ("Image dimensions (%dx%d) are too big. Max is %dx%d.",
466                        width, height, req->maximum_width, req->maximum_height);
467
468                 needs_conversion = TRUE;
469         }
470
471         /* If the data len is too big and no other conversion is needed,
472          * try with a lower factor. */
473         if (req->maximum_bytes > 0 && avatar->len > req->maximum_bytes && !needs_conversion) {
474                 DEBUG ("Image data (%"G_GSIZE_FORMAT" bytes) is too big "
475                        "(max is %u bytes), conversion needed.",
476                        avatar->len, req->maximum_bytes);
477
478                 factor = 0.5;
479                 needs_conversion = TRUE;
480         }
481
482         /* If no conversion is needed, return the avatar */
483         if (!needs_conversion) {
484                 g_free (new_format_name);
485                 g_free (new_mime_type);
486                 return empathy_avatar_ref (avatar);
487         }
488
489         do {
490                 GdkPixbuf *pixbuf_scaled = NULL;
491                 gboolean   saved;
492                 gint       new_width, new_height;
493                 gchar     *converted_image_data;
494                 gsize      converted_image_size;
495                 GError    *error = NULL;
496
497                 if (factor != 1) {
498                         new_width = width * factor;
499                         new_height = height * factor;
500                         pixbuf_scaled = gdk_pixbuf_scale_simple (pixbuf,
501                                                                  new_width,
502                                                                  new_height,
503                                                                  GDK_INTERP_HYPER);
504                 } else {
505                         new_width = width;
506                         new_height = height;
507                         pixbuf_scaled = g_object_ref (pixbuf);
508                 }
509
510                 DEBUG ("Trying with factor %f (%dx%d) and format %s...", factor,
511                         new_width, new_height, new_format_name);
512
513                 saved = gdk_pixbuf_save_to_buffer (pixbuf_scaled,
514                                                    &converted_image_data,
515                                                    &converted_image_size,
516                                                    new_format_name,
517                                                    &error, NULL);
518                 g_object_unref (pixbuf_scaled);
519
520                 if (!saved) {
521                         g_free (new_format_name);
522                         g_free (new_mime_type);
523                         avatar_chooser_error_show (chooser,
524                                 _("Couldn't convert image"),
525                                 error ? error->message : NULL);
526                         g_clear_error (&error);
527                         return NULL;
528                 }
529
530                 DEBUG ("Produced an image data of %"G_GSIZE_FORMAT" bytes.",
531                         converted_image_size);
532
533                 /* If the new image satisfy the req, keep it as current best */
534                 if (req->maximum_bytes == 0 ||
535                     converted_image_size <= req->maximum_bytes) {
536                         if (best_image_data)
537                                 g_free (best_image_data);
538
539                         best_image_data = converted_image_data;
540                         best_image_size = converted_image_size;
541
542                         /* If this image is close enough to the optimal size,
543                          * stop searching */
544                         if (req->maximum_bytes == 0 ||
545                             req->maximum_bytes - converted_image_size <= 1024)
546                                 break;
547                 } else {
548                         g_free (converted_image_data);
549                 }
550
551                 /* Make a binary search for the bigest factor that produce
552                  * an image data size less than max_size */
553                 if (converted_image_size > req->maximum_bytes)
554                         max_factor = factor;
555                 if (converted_image_size < req->maximum_bytes)
556                         min_factor = factor;
557                 factor = (min_factor + max_factor)/2;
558
559                 if ((int) (width * factor) == new_width ||
560                     (int) (height * factor) == new_height) {
561                         /* min_factor and max_factor are too close, so the new
562                          * factor will produce the same image as previous
563                          * iteration. No need to continue, we already found
564                          * the optimal size. */
565                         break;
566                 }
567
568                 /* Do 10 iterations in the worst case */
569         } while (++count < 10);
570
571         g_free (new_format_name);
572
573         /* Takes ownership of new_mime_type and best_image_data */
574         avatar = empathy_avatar_new ((guchar *) best_image_data,
575                 best_image_size, new_mime_type, NULL);
576
577         return avatar;
578 }
579
580 static void
581 avatar_chooser_clear_image (EmpathyAvatarChooser *chooser)
582 {
583         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
584         GtkWidget *image;
585
586         if (priv->avatar != NULL) {
587                 empathy_avatar_unref (priv->avatar);
588                 priv->avatar = NULL;
589         }
590
591         image = gtk_image_new_from_icon_name (EMPATHY_IMAGE_AVATAR_DEFAULT,
592                 GTK_ICON_SIZE_DIALOG);
593         gtk_button_set_image (GTK_BUTTON (chooser), image);
594         g_signal_emit (chooser, signals[CHANGED], 0);
595 }
596
597 static void
598 avatar_chooser_set_image_from_data (EmpathyAvatarChooser *chooser,
599                                     gchar                *data,
600                                     gsize                 size,
601                                     gboolean              set_locally)
602 {
603         GdkPixbuf     *pixbuf;
604         EmpathyAvatar *avatar = NULL;
605         gchar         *mime_type = NULL;
606
607         if (data == NULL) {
608                 avatar_chooser_clear_image (chooser);
609                 return;
610         }
611
612         pixbuf = empathy_pixbuf_from_data_and_mime (data, size, &mime_type);
613         if (pixbuf == NULL) {
614                 g_free (data);
615                 data = NULL;
616                 return;
617         }
618
619         /* avatar takes ownership of data and mime_type */
620         avatar = empathy_avatar_new ((guchar *) data, size, mime_type, NULL);
621
622         avatar_chooser_set_image (chooser, avatar, pixbuf, set_locally);
623 }
624
625 static void
626 avatar_chooser_set_image_from_avatar (EmpathyAvatarChooser *chooser,
627                                       EmpathyAvatar        *avatar,
628                                       gboolean              set_locally)
629 {
630         GdkPixbuf *pixbuf;
631         gchar     *mime_type = NULL;
632
633         g_assert (avatar != NULL);
634
635         pixbuf = empathy_pixbuf_from_data_and_mime ((gchar *) avatar->data,
636                                                     avatar->len,
637                                                     &mime_type);
638         if (pixbuf == NULL) {
639                 DEBUG ("couldn't make a pixbuf from avatar; giving up");
640                 return;
641         }
642
643         if (avatar->format == NULL) {
644                 avatar->format = mime_type;
645         } else {
646                 if (strcmp (mime_type, avatar->format)) {
647                         DEBUG ("avatar->format is %s; gdkpixbuf yields %s!",
648                                 avatar->format, mime_type);
649                 }
650                 g_free (mime_type);
651         }
652
653         empathy_avatar_ref (avatar);
654
655         avatar_chooser_set_image (chooser, avatar, pixbuf, set_locally);
656 }
657
658 static void
659 avatar_chooser_set_image (EmpathyAvatarChooser *chooser,
660                           EmpathyAvatar        *avatar,
661                           GdkPixbuf            *pixbuf,
662                           gboolean              set_locally)
663 {
664         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
665         GdkPixbuf                *pixbuf_view;
666         GtkWidget                *image;
667
668         g_assert (avatar != NULL);
669         g_assert (pixbuf != NULL);
670
671         if (set_locally) {
672                 EmpathyAvatar *conv;
673
674                 conv = avatar_chooser_maybe_convert_and_scale (chooser,
675                         pixbuf, avatar);
676                 empathy_avatar_unref (avatar);
677
678                 if (conv == NULL) {
679                         /* An error occured; don't change the avatar. */
680                         return;
681                 }
682
683                 avatar = conv;
684         }
685
686         if (priv->avatar != NULL) {
687                 empathy_avatar_unref (priv->avatar);
688         }
689         priv->avatar = avatar;
690
691         pixbuf_view = empathy_pixbuf_scale_down_if_necessary (pixbuf, AVATAR_SIZE_VIEW);
692         image = gtk_image_new_from_pixbuf (pixbuf_view);
693
694         gtk_button_set_image (GTK_BUTTON (chooser), image);
695         g_signal_emit (chooser, signals[CHANGED], 0);
696
697         g_object_unref (pixbuf_view);
698         g_object_unref (pixbuf);
699 }
700
701 static void
702 avatar_chooser_set_image_from_file (EmpathyAvatarChooser *chooser,
703                                     const gchar          *filename)
704 {
705         gchar  *image_data = NULL;
706         gsize   image_size = 0;
707         GError *error = NULL;
708
709         if (!g_file_get_contents (filename, &image_data, &image_size, &error)) {
710                 DEBUG ("Failed to load image from '%s': %s", filename,
711                         error ? error->message : "No error given");
712
713                 g_clear_error (&error);
714                 return;
715         }
716
717         avatar_chooser_set_image_from_data (chooser, image_data, image_size, TRUE);
718 }
719
720 static gboolean
721 avatar_chooser_drag_motion_cb (GtkWidget          *widget,
722                               GdkDragContext     *context,
723                               gint                x,
724                               gint                y,
725                               guint               time_,
726                               EmpathyAvatarChooser *chooser)
727 {
728         EmpathyAvatarChooserPriv *priv;
729         GList                  *p;
730
731         priv = GET_PRIV (chooser);
732
733         for (p = gdk_drag_context_list_targets (context); p != NULL;
734              p = p->next) {
735                 gchar *possible_type;
736
737                 possible_type = gdk_atom_name (GDK_POINTER_TO_ATOM (p->data));
738
739                 if (!strcmp (possible_type, URI_LIST_TYPE)) {
740                         g_free (possible_type);
741                         gdk_drag_status (context, GDK_ACTION_COPY, time_);
742
743                         return TRUE;
744                 }
745
746                 g_free (possible_type);
747         }
748
749         return FALSE;
750 }
751
752 static void
753 avatar_chooser_drag_leave_cb (GtkWidget          *widget,
754                              GdkDragContext     *context,
755                              guint               time_,
756                              EmpathyAvatarChooser *chooser)
757 {
758 }
759
760 static gboolean
761 avatar_chooser_drag_drop_cb (GtkWidget          *widget,
762                             GdkDragContext     *context,
763                             gint                x,
764                             gint                y,
765                             guint               time_,
766                             EmpathyAvatarChooser *chooser)
767 {
768         EmpathyAvatarChooserPriv *priv;
769         GList                  *p;
770
771         priv = GET_PRIV (chooser);
772
773         if (gdk_drag_context_list_targets (context) == NULL) {
774                 return FALSE;
775         }
776
777         for (p = gdk_drag_context_list_targets (context);
778              p != NULL; p = p->next) {
779                 char *possible_type;
780
781                 possible_type = gdk_atom_name (GDK_POINTER_TO_ATOM (p->data));
782                 if (!strcmp (possible_type, URI_LIST_TYPE)) {
783                         g_free (possible_type);
784                         gtk_drag_get_data (widget, context,
785                                            GDK_POINTER_TO_ATOM (p->data),
786                                            time_);
787
788                         return TRUE;
789                 }
790
791                 g_free (possible_type);
792         }
793
794         return FALSE;
795 }
796
797 static void
798 avatar_chooser_drag_data_received_cb (GtkWidget          *widget,
799                                      GdkDragContext     *context,
800                                      gint                x,
801                                      gint                y,
802                                      GtkSelectionData   *selection_data,
803                                      guint               info,
804                                      guint               time_,
805                                      EmpathyAvatarChooser *chooser)
806 {
807         gchar    *target_type;
808         gboolean  handled = FALSE;
809
810         target_type = gdk_atom_name (gtk_selection_data_get_target (selection_data));
811         if (!strcmp (target_type, URI_LIST_TYPE)) {
812                 GFile            *file;
813                 gchar            *nl;
814                 gchar            *data = NULL;
815                 gsize             bytes_read;
816
817                 nl = strstr ((gchar *) gtk_selection_data_get_data (selection_data),
818                                                 "\r\n");
819                 if (nl) {
820                         gchar *uri;
821
822                         uri = g_strndup ((gchar *) gtk_selection_data_get_data (selection_data),
823                                          nl - (gchar *) gtk_selection_data_get_data (selection_data));
824
825                         file = g_file_new_for_uri (uri);
826                         g_free (uri);
827                 } else {
828                         file = g_file_new_for_uri ((gchar *) gtk_selection_data_get_data (
829                                                 selection_data));
830                 }
831
832                 handled = g_file_load_contents (file, NULL, &data, &bytes_read,
833                                                 NULL, NULL);
834
835                 if (handled) {
836                         /* this in turn calls empathy_avatar_new (), which assumes
837                          * ownership of data.
838                          */
839                         avatar_chooser_set_image_from_data (chooser, data,
840                                                             bytes_read,
841                                                             TRUE);
842                 }
843
844                 g_object_unref (file);
845         }
846
847         gtk_drag_finish (context, handled, FALSE, time_);
848 }
849
850 static void
851 avatar_chooser_update_preview_cb (GtkFileChooser       *file_chooser,
852                                   EmpathyAvatarChooser *chooser)
853 {
854         gchar *filename;
855
856         filename = gtk_file_chooser_get_preview_filename (file_chooser);
857
858         if (filename) {
859                 GtkWidget *image;
860                 GdkPixbuf *pixbuf = NULL;
861                 GdkPixbuf *scaled_pixbuf;
862
863                 pixbuf = gdk_pixbuf_new_from_file (filename, NULL);
864
865                 image = gtk_file_chooser_get_preview_widget (file_chooser);
866
867                 if (pixbuf) {
868                         scaled_pixbuf = empathy_pixbuf_scale_down_if_necessary (pixbuf, AVATAR_SIZE_SAVE);
869                         gtk_image_set_from_pixbuf (GTK_IMAGE (image), scaled_pixbuf);
870                         g_object_unref (scaled_pixbuf);
871                         g_object_unref (pixbuf);
872                 } else {
873                         gtk_image_set_from_stock (GTK_IMAGE (image),
874                                                   "gtk-dialog-question",
875                                                   GTK_ICON_SIZE_DIALOG);
876                 }
877
878                 g_free (filename);
879         }
880
881         gtk_file_chooser_set_preview_widget_active (file_chooser, TRUE);
882 }
883
884 static void
885 avatar_chooser_response_cb (GtkWidget            *widget,
886                             gint                  response,
887                             EmpathyAvatarChooser *chooser)
888 {
889         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
890
891         priv->chooser_dialog = NULL;
892
893         if (response == GTK_RESPONSE_OK) {
894                 gchar *filename;
895                 gchar *path;
896
897                 filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (widget));
898                 avatar_chooser_set_image_from_file (chooser, filename);
899                 g_free (filename);
900
901                 path = gtk_file_chooser_get_current_folder (GTK_FILE_CHOOSER (widget));
902                 if (path) {
903                         g_settings_set_string (priv->gsettings_ui,
904                                                EMPATHY_PREFS_UI_AVATAR_DIRECTORY,
905                                                path);
906
907                         g_free (path);
908                 }
909         }
910         else if (response == GTK_RESPONSE_NO) {
911                 /* This corresponds to "No Image", not to "Cancel" */
912                 avatar_chooser_clear_image (chooser);
913         }
914
915         gtk_widget_destroy (widget);
916 }
917
918 static void
919 avatar_chooser_clicked_cb (GtkWidget            *button,
920                            EmpathyAvatarChooser *chooser)
921 {
922         GtkFileChooser *chooser_dialog;
923         GtkWidget      *image;
924         gchar          *saved_dir = NULL;
925         const gchar    *default_dir = DEFAULT_DIR;
926         const gchar    *pics_dir;
927         GtkFileFilter  *filter;
928         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
929
930         if (priv->chooser_dialog) {
931                 gtk_window_present (GTK_WINDOW (priv->chooser_dialog));
932                 return;
933         }
934
935         priv->chooser_dialog = GTK_FILE_CHOOSER (
936                 gtk_file_chooser_dialog_new (_("Select Your Avatar Image"),
937                                              empathy_get_toplevel_window (GTK_WIDGET (chooser)),
938                                              GTK_FILE_CHOOSER_ACTION_OPEN,
939                                              _("No Image"),
940                                              GTK_RESPONSE_NO,
941                                              GTK_STOCK_CANCEL,
942                                              GTK_RESPONSE_CANCEL,
943                                              GTK_STOCK_OPEN,
944                                              GTK_RESPONSE_OK,
945                                              NULL));
946         chooser_dialog = priv->chooser_dialog;
947         gtk_window_set_destroy_with_parent (GTK_WINDOW (chooser_dialog), TRUE);
948
949         /* Get special dirs */
950         saved_dir = g_settings_get_string (priv->gsettings_ui,
951                                            EMPATHY_PREFS_UI_AVATAR_DIRECTORY);
952
953         if (saved_dir && !g_file_test (saved_dir, G_FILE_TEST_IS_DIR)) {
954                 g_free (saved_dir);
955                 saved_dir = NULL;
956         }
957         if (!g_file_test (default_dir, G_FILE_TEST_IS_DIR)) {
958                 default_dir = NULL;
959         }
960         pics_dir = g_get_user_special_dir (G_USER_DIRECTORY_PICTURES);
961         if (pics_dir && !g_file_test (pics_dir, G_FILE_TEST_IS_DIR)) {
962                 pics_dir = NULL;
963         }
964
965         /* Set current dir to the last one or to DEFAULT_DIR or to home */
966         if (saved_dir) {
967                 gtk_file_chooser_set_current_folder (chooser_dialog, saved_dir);
968         }
969         else if (pics_dir) {
970                 gtk_file_chooser_set_current_folder (chooser_dialog, pics_dir);
971         }
972         else if (default_dir) {
973                 gtk_file_chooser_set_current_folder (chooser_dialog, default_dir);
974         } else {
975                 gtk_file_chooser_set_current_folder (chooser_dialog, g_get_home_dir ());
976         }
977
978         /* Add shortcuts to special dirs */
979         if (saved_dir) {
980                 gtk_file_chooser_add_shortcut_folder (chooser_dialog, saved_dir, NULL);
981         }
982         else if (pics_dir) {
983                 gtk_file_chooser_add_shortcut_folder (chooser_dialog, pics_dir, NULL);
984         }
985         if (default_dir) {
986                 gtk_file_chooser_add_shortcut_folder (chooser_dialog, default_dir, NULL);
987         }
988
989         /* Setup preview image */
990         image = gtk_image_new ();
991         gtk_file_chooser_set_preview_widget (chooser_dialog, image);
992         gtk_widget_set_size_request (image, AVATAR_SIZE_SAVE, AVATAR_SIZE_SAVE);
993         gtk_widget_show (image);
994         gtk_file_chooser_set_use_preview_label (chooser_dialog, FALSE);
995         g_signal_connect (chooser_dialog, "update-preview",
996                           G_CALLBACK (avatar_chooser_update_preview_cb),
997                           chooser);
998
999         /* Setup filers */
1000         filter = gtk_file_filter_new ();
1001         gtk_file_filter_set_name (filter, _("Images"));
1002         gtk_file_filter_add_pixbuf_formats (filter);
1003         gtk_file_chooser_add_filter (chooser_dialog, filter);
1004         filter = gtk_file_filter_new ();
1005         gtk_file_filter_set_name (filter, _("All Files"));
1006         gtk_file_filter_add_pattern (filter, "*");
1007         gtk_file_chooser_add_filter (chooser_dialog, filter);
1008
1009         /* Setup response */
1010         gtk_dialog_set_default_response (GTK_DIALOG (chooser_dialog), GTK_RESPONSE_OK);
1011         g_signal_connect (chooser_dialog, "response",
1012                           G_CALLBACK (avatar_chooser_response_cb),
1013                           chooser);
1014
1015         gtk_widget_show (GTK_WIDGET (chooser_dialog));
1016
1017         g_free (saved_dir);
1018 }
1019
1020 /**
1021  * empathy_avatar_chooser_new:
1022  *
1023  * Creates a new #EmpathyAvatarChooser.
1024  *
1025  * Return value: a new #EmpathyAvatarChooser
1026  */
1027 GtkWidget *
1028 empathy_avatar_chooser_new (void)
1029 {
1030         return g_object_new (EMPATHY_TYPE_AVATAR_CHOOSER, NULL);
1031 }
1032
1033 /**
1034  * empathy_avatar_chooser_set:
1035  * @chooser: an #EmpathyAvatarChooser
1036  * @avatar: a new #EmpathyAvatar
1037  *
1038  * Sets the @chooser to display the avatar indicated by @avatar.
1039  */
1040 void
1041 empathy_avatar_chooser_set (EmpathyAvatarChooser *chooser,
1042                             EmpathyAvatar        *avatar)
1043 {
1044         g_return_if_fail (EMPATHY_IS_AVATAR_CHOOSER (chooser));
1045
1046         if (avatar != NULL) {
1047                 avatar_chooser_set_image_from_avatar (chooser, avatar, FALSE);
1048         } else {
1049                 avatar_chooser_clear_image (chooser);
1050         }
1051 }
1052
1053 /**
1054  * empathy_avatar_chooser_get_image_data:
1055  * @chooser: an #EmpathyAvatarChooser
1056  * @data: avatar bytes
1057  * @data_size: size of @data
1058  * @mime_type: avatar mime-type
1059  *
1060  * Gets image data about the currently selected avatar.
1061  */
1062 void
1063 empathy_avatar_chooser_get_image_data (EmpathyAvatarChooser  *chooser,
1064                                        const gchar          **data,
1065                                        gsize                 *data_size,
1066                                        const gchar          **mime_type)
1067 {
1068         EmpathyAvatarChooserPriv *priv;
1069
1070         g_return_if_fail (EMPATHY_IS_AVATAR_CHOOSER (chooser));
1071
1072         priv = GET_PRIV (chooser);
1073
1074         if (priv->avatar != NULL) {
1075                 if (data != NULL) {
1076                         *data = (gchar *) priv->avatar->data;
1077                 }
1078                 if (data_size != NULL) {
1079                         *data_size = priv->avatar->len;
1080                 }
1081                 if (mime_type != NULL) {
1082                         *mime_type = priv->avatar->format;
1083                 }
1084         } else {
1085                 if (data != NULL) {
1086                         *data = NULL;
1087                 }
1088                 if (data_size != NULL) {
1089                         *data_size = 0;
1090                 }
1091                 if (mime_type != NULL) {
1092                         *mime_type = NULL;
1093                 }
1094         }
1095 }
1096
1097 void
1098 empathy_avatar_chooser_set_account (EmpathyAvatarChooser *self,
1099                                        TpAccount *account)
1100 {
1101         g_return_if_fail (account != NULL);
1102
1103         avatar_chooser_set_connection (self, tp_account_get_connection (account));
1104         g_object_notify (G_OBJECT (self), "connection");
1105 }