]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-avatar-chooser.c
Updated kn translations
[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         GList                  *p;
729
730         for (p = gdk_drag_context_list_targets (context); p != NULL;
731              p = p->next) {
732                 gchar *possible_type;
733
734                 possible_type = gdk_atom_name (GDK_POINTER_TO_ATOM (p->data));
735
736                 if (!strcmp (possible_type, URI_LIST_TYPE)) {
737                         g_free (possible_type);
738                         gdk_drag_status (context, GDK_ACTION_COPY, time_);
739
740                         return TRUE;
741                 }
742
743                 g_free (possible_type);
744         }
745
746         return FALSE;
747 }
748
749 static void
750 avatar_chooser_drag_leave_cb (GtkWidget          *widget,
751                              GdkDragContext     *context,
752                              guint               time_,
753                              EmpathyAvatarChooser *chooser)
754 {
755 }
756
757 static gboolean
758 avatar_chooser_drag_drop_cb (GtkWidget          *widget,
759                             GdkDragContext     *context,
760                             gint                x,
761                             gint                y,
762                             guint               time_,
763                             EmpathyAvatarChooser *chooser)
764 {
765         GList                  *p;
766
767         if (gdk_drag_context_list_targets (context) == NULL) {
768                 return FALSE;
769         }
770
771         for (p = gdk_drag_context_list_targets (context);
772              p != NULL; p = p->next) {
773                 char *possible_type;
774
775                 possible_type = gdk_atom_name (GDK_POINTER_TO_ATOM (p->data));
776                 if (!strcmp (possible_type, URI_LIST_TYPE)) {
777                         g_free (possible_type);
778                         gtk_drag_get_data (widget, context,
779                                            GDK_POINTER_TO_ATOM (p->data),
780                                            time_);
781
782                         return TRUE;
783                 }
784
785                 g_free (possible_type);
786         }
787
788         return FALSE;
789 }
790
791 static void
792 avatar_chooser_drag_data_received_cb (GtkWidget          *widget,
793                                      GdkDragContext     *context,
794                                      gint                x,
795                                      gint                y,
796                                      GtkSelectionData   *selection_data,
797                                      guint               info,
798                                      guint               time_,
799                                      EmpathyAvatarChooser *chooser)
800 {
801         gchar    *target_type;
802         gboolean  handled = FALSE;
803
804         target_type = gdk_atom_name (gtk_selection_data_get_target (selection_data));
805         if (!strcmp (target_type, URI_LIST_TYPE)) {
806                 GFile            *file;
807                 gchar            *nl;
808                 gchar            *data = NULL;
809                 gsize             bytes_read;
810
811                 nl = strstr ((gchar *) gtk_selection_data_get_data (selection_data),
812                                                 "\r\n");
813                 if (nl) {
814                         gchar *uri;
815
816                         uri = g_strndup ((gchar *) gtk_selection_data_get_data (selection_data),
817                                          nl - (gchar *) gtk_selection_data_get_data (selection_data));
818
819                         file = g_file_new_for_uri (uri);
820                         g_free (uri);
821                 } else {
822                         file = g_file_new_for_uri ((gchar *) gtk_selection_data_get_data (
823                                                 selection_data));
824                 }
825
826                 handled = g_file_load_contents (file, NULL, &data, &bytes_read,
827                                                 NULL, NULL);
828
829                 if (handled) {
830                         /* this in turn calls empathy_avatar_new (), which assumes
831                          * ownership of data.
832                          */
833                         avatar_chooser_set_image_from_data (chooser, data,
834                                                             bytes_read,
835                                                             TRUE);
836                 }
837
838                 g_object_unref (file);
839         }
840
841         gtk_drag_finish (context, handled, FALSE, time_);
842 }
843
844 static void
845 avatar_chooser_update_preview_cb (GtkFileChooser       *file_chooser,
846                                   EmpathyAvatarChooser *chooser)
847 {
848         gchar *filename;
849
850         filename = gtk_file_chooser_get_preview_filename (file_chooser);
851
852         if (filename) {
853                 GtkWidget *image;
854                 GdkPixbuf *pixbuf = NULL;
855                 GdkPixbuf *scaled_pixbuf;
856
857                 pixbuf = gdk_pixbuf_new_from_file (filename, NULL);
858
859                 image = gtk_file_chooser_get_preview_widget (file_chooser);
860
861                 if (pixbuf) {
862                         scaled_pixbuf = empathy_pixbuf_scale_down_if_necessary (pixbuf, AVATAR_SIZE_SAVE);
863                         gtk_image_set_from_pixbuf (GTK_IMAGE (image), scaled_pixbuf);
864                         g_object_unref (scaled_pixbuf);
865                         g_object_unref (pixbuf);
866                 } else {
867                         gtk_image_set_from_stock (GTK_IMAGE (image),
868                                                   "gtk-dialog-question",
869                                                   GTK_ICON_SIZE_DIALOG);
870                 }
871
872                 g_free (filename);
873         }
874
875         gtk_file_chooser_set_preview_widget_active (file_chooser, TRUE);
876 }
877
878 static void
879 avatar_chooser_response_cb (GtkWidget            *widget,
880                             gint                  response,
881                             EmpathyAvatarChooser *chooser)
882 {
883         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
884
885         priv->chooser_dialog = NULL;
886
887         if (response == GTK_RESPONSE_OK) {
888                 gchar *filename;
889                 gchar *path;
890
891                 filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (widget));
892                 avatar_chooser_set_image_from_file (chooser, filename);
893                 g_free (filename);
894
895                 path = gtk_file_chooser_get_current_folder (GTK_FILE_CHOOSER (widget));
896                 if (path) {
897                         g_settings_set_string (priv->gsettings_ui,
898                                                EMPATHY_PREFS_UI_AVATAR_DIRECTORY,
899                                                path);
900
901                         g_free (path);
902                 }
903         }
904         else if (response == GTK_RESPONSE_NO) {
905                 /* This corresponds to "No Image", not to "Cancel" */
906                 avatar_chooser_clear_image (chooser);
907         }
908
909         gtk_widget_destroy (widget);
910 }
911
912 static void
913 avatar_chooser_clicked_cb (GtkWidget            *button,
914                            EmpathyAvatarChooser *chooser)
915 {
916         GtkFileChooser *chooser_dialog;
917         GtkWidget      *image;
918         gchar          *saved_dir = NULL;
919         const gchar    *default_dir = DEFAULT_DIR;
920         const gchar    *pics_dir;
921         GtkFileFilter  *filter;
922         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
923
924         if (priv->chooser_dialog) {
925                 gtk_window_present (GTK_WINDOW (priv->chooser_dialog));
926                 return;
927         }
928
929         priv->chooser_dialog = GTK_FILE_CHOOSER (
930                 gtk_file_chooser_dialog_new (_("Select Your Avatar Image"),
931                                              empathy_get_toplevel_window (GTK_WIDGET (chooser)),
932                                              GTK_FILE_CHOOSER_ACTION_OPEN,
933                                              _("No Image"),
934                                              GTK_RESPONSE_NO,
935                                              GTK_STOCK_CANCEL,
936                                              GTK_RESPONSE_CANCEL,
937                                              GTK_STOCK_OPEN,
938                                              GTK_RESPONSE_OK,
939                                              NULL));
940         chooser_dialog = priv->chooser_dialog;
941         gtk_window_set_destroy_with_parent (GTK_WINDOW (chooser_dialog), TRUE);
942
943         /* Get special dirs */
944         saved_dir = g_settings_get_string (priv->gsettings_ui,
945                                            EMPATHY_PREFS_UI_AVATAR_DIRECTORY);
946
947         if (saved_dir && !g_file_test (saved_dir, G_FILE_TEST_IS_DIR)) {
948                 g_free (saved_dir);
949                 saved_dir = NULL;
950         }
951         if (!g_file_test (default_dir, G_FILE_TEST_IS_DIR)) {
952                 default_dir = NULL;
953         }
954         pics_dir = g_get_user_special_dir (G_USER_DIRECTORY_PICTURES);
955         if (pics_dir && !g_file_test (pics_dir, G_FILE_TEST_IS_DIR)) {
956                 pics_dir = NULL;
957         }
958
959         /* Set current dir to the last one or to DEFAULT_DIR or to home */
960         if (saved_dir) {
961                 gtk_file_chooser_set_current_folder (chooser_dialog, saved_dir);
962         }
963         else if (pics_dir) {
964                 gtk_file_chooser_set_current_folder (chooser_dialog, pics_dir);
965         }
966         else if (default_dir) {
967                 gtk_file_chooser_set_current_folder (chooser_dialog, default_dir);
968         } else {
969                 gtk_file_chooser_set_current_folder (chooser_dialog, g_get_home_dir ());
970         }
971
972         /* Add shortcuts to special dirs */
973         if (saved_dir) {
974                 gtk_file_chooser_add_shortcut_folder (chooser_dialog, saved_dir, NULL);
975         }
976         else if (pics_dir) {
977                 gtk_file_chooser_add_shortcut_folder (chooser_dialog, pics_dir, NULL);
978         }
979         if (default_dir) {
980                 gtk_file_chooser_add_shortcut_folder (chooser_dialog, default_dir, NULL);
981         }
982
983         /* Setup preview image */
984         image = gtk_image_new ();
985         gtk_file_chooser_set_preview_widget (chooser_dialog, image);
986         gtk_widget_set_size_request (image, AVATAR_SIZE_SAVE, AVATAR_SIZE_SAVE);
987         gtk_widget_show (image);
988         gtk_file_chooser_set_use_preview_label (chooser_dialog, FALSE);
989         g_signal_connect (chooser_dialog, "update-preview",
990                           G_CALLBACK (avatar_chooser_update_preview_cb),
991                           chooser);
992
993         /* Setup filers */
994         filter = gtk_file_filter_new ();
995         gtk_file_filter_set_name (filter, _("Images"));
996         gtk_file_filter_add_pixbuf_formats (filter);
997         gtk_file_chooser_add_filter (chooser_dialog, filter);
998         filter = gtk_file_filter_new ();
999         gtk_file_filter_set_name (filter, _("All Files"));
1000         gtk_file_filter_add_pattern (filter, "*");
1001         gtk_file_chooser_add_filter (chooser_dialog, filter);
1002
1003         /* Setup response */
1004         gtk_dialog_set_default_response (GTK_DIALOG (chooser_dialog), GTK_RESPONSE_OK);
1005         g_signal_connect (chooser_dialog, "response",
1006                           G_CALLBACK (avatar_chooser_response_cb),
1007                           chooser);
1008
1009         gtk_widget_show (GTK_WIDGET (chooser_dialog));
1010
1011         g_free (saved_dir);
1012 }
1013
1014 /**
1015  * empathy_avatar_chooser_new:
1016  *
1017  * Creates a new #EmpathyAvatarChooser.
1018  *
1019  * Return value: a new #EmpathyAvatarChooser
1020  */
1021 GtkWidget *
1022 empathy_avatar_chooser_new (void)
1023 {
1024         return g_object_new (EMPATHY_TYPE_AVATAR_CHOOSER, NULL);
1025 }
1026
1027 /**
1028  * empathy_avatar_chooser_set:
1029  * @chooser: an #EmpathyAvatarChooser
1030  * @avatar: a new #EmpathyAvatar
1031  *
1032  * Sets the @chooser to display the avatar indicated by @avatar.
1033  */
1034 void
1035 empathy_avatar_chooser_set (EmpathyAvatarChooser *chooser,
1036                             EmpathyAvatar        *avatar)
1037 {
1038         g_return_if_fail (EMPATHY_IS_AVATAR_CHOOSER (chooser));
1039
1040         if (avatar != NULL) {
1041                 avatar_chooser_set_image_from_avatar (chooser, avatar, FALSE);
1042         } else {
1043                 avatar_chooser_clear_image (chooser);
1044         }
1045 }
1046
1047 /**
1048  * empathy_avatar_chooser_get_image_data:
1049  * @chooser: an #EmpathyAvatarChooser
1050  * @data: avatar bytes
1051  * @data_size: size of @data
1052  * @mime_type: avatar mime-type
1053  *
1054  * Gets image data about the currently selected avatar.
1055  */
1056 void
1057 empathy_avatar_chooser_get_image_data (EmpathyAvatarChooser  *chooser,
1058                                        const gchar          **data,
1059                                        gsize                 *data_size,
1060                                        const gchar          **mime_type)
1061 {
1062         EmpathyAvatarChooserPriv *priv;
1063
1064         g_return_if_fail (EMPATHY_IS_AVATAR_CHOOSER (chooser));
1065
1066         priv = GET_PRIV (chooser);
1067
1068         if (priv->avatar != NULL) {
1069                 if (data != NULL) {
1070                         *data = (gchar *) priv->avatar->data;
1071                 }
1072                 if (data_size != NULL) {
1073                         *data_size = priv->avatar->len;
1074                 }
1075                 if (mime_type != NULL) {
1076                         *mime_type = priv->avatar->format;
1077                 }
1078         } else {
1079                 if (data != NULL) {
1080                         *data = NULL;
1081                 }
1082                 if (data_size != NULL) {
1083                         *data_size = 0;
1084                 }
1085                 if (mime_type != NULL) {
1086                         *mime_type = NULL;
1087                 }
1088         }
1089 }
1090
1091 void
1092 empathy_avatar_chooser_set_account (EmpathyAvatarChooser *self,
1093                                        TpAccount *account)
1094 {
1095         g_return_if_fail (account != NULL);
1096
1097         avatar_chooser_set_connection (self, tp_account_get_connection (account));
1098         g_object_notify (G_OBJECT (self), "connection");
1099 }