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