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