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