]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-avatar-chooser.c
don't build avatar_chooser_set_avatar_from_pixbuf if building without cheese
[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 #ifdef HAVE_CHEESE
738 static void
739 avatar_chooser_set_avatar_from_pixbuf (EmpathyAvatarChooser *chooser,
740                                        GdkPixbuf            *pb)
741 {
742         /* dup the string as empathy_avatar_new steals ownership of the it */
743         gchar         *mime = g_strdup ("image/png");
744         gsize          size;
745         gchar         *buf;
746         EmpathyAvatar *avatar = NULL;
747         GError        *error = NULL;
748         if (!gdk_pixbuf_save_to_buffer (pb, &buf, &size, "png", &error, NULL)) {
749                 avatar_chooser_error_show (chooser,
750                         _("Couldn't save pixbuf to png"),
751                         error ? error->message : NULL);
752                 g_clear_error (&error);
753                 return;
754         }
755         avatar = empathy_avatar_new ((guchar *) buf, size, mime, NULL);
756         avatar_chooser_set_image (chooser, avatar, pb, TRUE);
757 }
758 #endif
759
760 static gboolean
761 avatar_chooser_drag_motion_cb (GtkWidget          *widget,
762                               GdkDragContext     *context,
763                               gint                x,
764                               gint                y,
765                               guint               time_,
766                               EmpathyAvatarChooser *chooser)
767 {
768         GList                  *p;
769
770         for (p = gdk_drag_context_list_targets (context); p != NULL;
771              p = p->next) {
772                 gchar *possible_type;
773
774                 possible_type = gdk_atom_name (GDK_POINTER_TO_ATOM (p->data));
775
776                 if (!strcmp (possible_type, URI_LIST_TYPE)) {
777                         g_free (possible_type);
778                         gdk_drag_status (context, GDK_ACTION_COPY, time_);
779
780                         return TRUE;
781                 }
782
783                 g_free (possible_type);
784         }
785
786         return FALSE;
787 }
788
789 static void
790 avatar_chooser_drag_leave_cb (GtkWidget          *widget,
791                              GdkDragContext     *context,
792                              guint               time_,
793                              EmpathyAvatarChooser *chooser)
794 {
795 }
796
797 static gboolean
798 avatar_chooser_drag_drop_cb (GtkWidget          *widget,
799                             GdkDragContext     *context,
800                             gint                x,
801                             gint                y,
802                             guint               time_,
803                             EmpathyAvatarChooser *chooser)
804 {
805         GList                  *p;
806
807         if (gdk_drag_context_list_targets (context) == NULL) {
808                 return FALSE;
809         }
810
811         for (p = gdk_drag_context_list_targets (context);
812              p != NULL; p = p->next) {
813                 char *possible_type;
814
815                 possible_type = gdk_atom_name (GDK_POINTER_TO_ATOM (p->data));
816                 if (!strcmp (possible_type, URI_LIST_TYPE)) {
817                         g_free (possible_type);
818                         gtk_drag_get_data (widget, context,
819                                            GDK_POINTER_TO_ATOM (p->data),
820                                            time_);
821
822                         return TRUE;
823                 }
824
825                 g_free (possible_type);
826         }
827
828         return FALSE;
829 }
830
831 static void
832 avatar_chooser_drag_data_received_cb (GtkWidget          *widget,
833                                      GdkDragContext     *context,
834                                      gint                x,
835                                      gint                y,
836                                      GtkSelectionData   *selection_data,
837                                      guint               info,
838                                      guint               time_,
839                                      EmpathyAvatarChooser *chooser)
840 {
841         gchar    *target_type;
842         gboolean  handled = FALSE;
843
844         target_type = gdk_atom_name (gtk_selection_data_get_target (selection_data));
845         if (!strcmp (target_type, URI_LIST_TYPE)) {
846                 GFile            *file;
847                 gchar            *nl;
848                 gchar            *data = NULL;
849                 gsize             bytes_read;
850
851                 nl = strstr ((gchar *) gtk_selection_data_get_data (selection_data),
852                                                 "\r\n");
853                 if (nl) {
854                         gchar *uri;
855
856                         uri = g_strndup ((gchar *) gtk_selection_data_get_data (selection_data),
857                                          nl - (gchar *) gtk_selection_data_get_data (selection_data));
858
859                         file = g_file_new_for_uri (uri);
860                         g_free (uri);
861                 } else {
862                         file = g_file_new_for_uri ((gchar *) gtk_selection_data_get_data (
863                                                 selection_data));
864                 }
865
866                 handled = g_file_load_contents (file, NULL, &data, &bytes_read,
867                                                 NULL, NULL);
868
869                 if (handled) {
870                         /* this in turn calls empathy_avatar_new (), which assumes
871                          * ownership of data.
872                          */
873                         avatar_chooser_set_image_from_data (chooser, data,
874                                                             bytes_read,
875                                                             TRUE);
876                 }
877
878                 g_object_unref (file);
879         }
880
881         gtk_drag_finish (context, handled, FALSE, time_);
882 }
883
884 static void
885 avatar_chooser_update_preview_cb (GtkFileChooser       *file_chooser,
886                                   EmpathyAvatarChooser *chooser)
887 {
888         gchar *filename;
889
890         filename = gtk_file_chooser_get_preview_filename (file_chooser);
891
892         if (filename) {
893                 GtkWidget *image;
894                 GdkPixbuf *pixbuf = NULL;
895                 GdkPixbuf *scaled_pixbuf;
896
897                 pixbuf = gdk_pixbuf_new_from_file (filename, NULL);
898
899                 image = gtk_file_chooser_get_preview_widget (file_chooser);
900
901                 if (pixbuf) {
902                         scaled_pixbuf = empathy_pixbuf_scale_down_if_necessary (pixbuf, AVATAR_SIZE_SAVE);
903                         gtk_image_set_from_pixbuf (GTK_IMAGE (image), scaled_pixbuf);
904                         g_object_unref (scaled_pixbuf);
905                         g_object_unref (pixbuf);
906                 } else {
907                         gtk_image_set_from_stock (GTK_IMAGE (image),
908                                                   "gtk-dialog-question",
909                                                   GTK_ICON_SIZE_DIALOG);
910                 }
911
912                 g_free (filename);
913         }
914
915         gtk_file_chooser_set_preview_widget_active (file_chooser, TRUE);
916 }
917
918 #ifdef HAVE_CHEESE
919 static gboolean
920 destroy_chooser (GtkWidget *chooser)
921 {
922         gtk_widget_destroy (chooser);
923         return FALSE;
924 }
925
926 static void
927 webcam_response_cb (GtkDialog            *dialog,
928                     int                   response,
929                     EmpathyAvatarChooser *chooser)
930 {
931         if (response == GTK_RESPONSE_ACCEPT) {
932                 GdkPixbuf           *pb;
933                 CheeseAvatarChooser *cheese_chooser;
934
935                 cheese_chooser = CHEESE_AVATAR_CHOOSER (dialog);
936                 pb = cheese_avatar_chooser_get_picture (cheese_chooser);
937                 avatar_chooser_set_avatar_from_pixbuf (chooser, pb);
938         }
939         if (response != GTK_RESPONSE_DELETE_EVENT &&
940             response != GTK_RESPONSE_NONE)
941                 g_idle_add ((GSourceFunc) destroy_chooser, dialog);
942 }
943
944 static void
945 choose_avatar_from_webcam (GtkWidget            *widget,
946                            EmpathyAvatarChooser *chooser)
947 {
948         GtkWidget *window;
949
950         window = cheese_avatar_chooser_new ();
951
952         gtk_window_set_transient_for (GTK_WINDOW (window),
953                                       GTK_WINDOW (empathy_get_toplevel_window (GTK_WIDGET (chooser))));
954         gtk_window_set_modal (GTK_WINDOW (window), TRUE);
955         g_signal_connect (G_OBJECT (window), "response",
956                           G_CALLBACK (webcam_response_cb), chooser);
957         gtk_widget_show (window);
958 }
959 #endif /* HAVE_CHEESE */
960
961 static void
962 avatar_chooser_response_cb (GtkWidget            *widget,
963                             gint                  response,
964                             EmpathyAvatarChooser *chooser)
965 {
966         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
967
968         priv->chooser_dialog = NULL;
969
970         if (response == EMPATHY_AVATAR_CHOOSER_RESPONSE_FILE) {
971                 gchar *filename;
972                 gchar *path;
973
974                 filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (widget));
975                 avatar_chooser_set_image_from_file (chooser, filename);
976                 g_free (filename);
977
978                 path = gtk_file_chooser_get_current_folder (GTK_FILE_CHOOSER (widget));
979                 if (path) {
980                         g_settings_set_string (priv->gsettings_ui,
981                                                EMPATHY_PREFS_UI_AVATAR_DIRECTORY,
982                                                path);
983
984                         g_free (path);
985                 }
986         }
987         else if (response == EMPATHY_AVATAR_CHOOSER_RESPONSE_NO_IMAGE) {
988                 /* This corresponds to "No Image", not to "Cancel" */
989                 avatar_chooser_clear_image (chooser);
990         }
991         #ifdef HAVE_CHEESE
992         else if (response == EMPATHY_AVATAR_CHOOSER_RESPONSE_WEBCAM) {
993                 /* This corresponds to "Camera Picture" */
994                 choose_avatar_from_webcam (widget, chooser);
995         }
996         #endif
997         gtk_widget_destroy (widget);
998 }
999
1000 static void
1001 avatar_chooser_clicked_cb (GtkWidget            *button,
1002                            EmpathyAvatarChooser *chooser)
1003 {
1004         GtkFileChooser *chooser_dialog;
1005         GtkWidget      *image;
1006         gchar          *saved_dir = NULL;
1007         const gchar    *default_dir = DEFAULT_DIR;
1008         const gchar    *pics_dir;
1009         GtkFileFilter  *filter;
1010         EmpathyAvatarChooserPriv *priv = GET_PRIV (chooser);
1011
1012         if (priv->chooser_dialog) {
1013                 gtk_window_present (GTK_WINDOW (priv->chooser_dialog));
1014                 return;
1015         }
1016
1017         priv->chooser_dialog = GTK_FILE_CHOOSER (
1018                 gtk_file_chooser_dialog_new (_("Select Your Avatar Image"),
1019                                              empathy_get_toplevel_window (GTK_WIDGET (chooser)),
1020                                              GTK_FILE_CHOOSER_ACTION_OPEN,
1021                                              #ifdef HAVE_CHEESE
1022                                              _("Take a picture..."),
1023                                              EMPATHY_AVATAR_CHOOSER_RESPONSE_WEBCAM,
1024                                              #endif
1025                                              _("No Image"),
1026                                              EMPATHY_AVATAR_CHOOSER_RESPONSE_NO_IMAGE,
1027                                              GTK_STOCK_CANCEL,
1028                                              EMPATHY_AVATAR_CHOOSER_RESPONSE_CANCEL,
1029                                              GTK_STOCK_OPEN,
1030                                              EMPATHY_AVATAR_CHOOSER_RESPONSE_FILE,
1031                                              NULL));
1032         chooser_dialog = priv->chooser_dialog;
1033         gtk_window_set_destroy_with_parent (GTK_WINDOW (chooser_dialog), TRUE);
1034
1035         /* Get special dirs */
1036         saved_dir = g_settings_get_string (priv->gsettings_ui,
1037                                            EMPATHY_PREFS_UI_AVATAR_DIRECTORY);
1038
1039         if (saved_dir && !g_file_test (saved_dir, G_FILE_TEST_IS_DIR)) {
1040                 g_free (saved_dir);
1041                 saved_dir = NULL;
1042         }
1043         if (!g_file_test (default_dir, G_FILE_TEST_IS_DIR)) {
1044                 default_dir = NULL;
1045         }
1046         pics_dir = g_get_user_special_dir (G_USER_DIRECTORY_PICTURES);
1047         if (pics_dir && !g_file_test (pics_dir, G_FILE_TEST_IS_DIR)) {
1048                 pics_dir = NULL;
1049         }
1050
1051         /* Set current dir to the last one or to DEFAULT_DIR or to home */
1052         if (saved_dir) {
1053                 gtk_file_chooser_set_current_folder (chooser_dialog, saved_dir);
1054         }
1055         else if (pics_dir) {
1056                 gtk_file_chooser_set_current_folder (chooser_dialog, pics_dir);
1057         }
1058         else if (default_dir) {
1059                 gtk_file_chooser_set_current_folder (chooser_dialog, default_dir);
1060         } else {
1061                 gtk_file_chooser_set_current_folder (chooser_dialog, g_get_home_dir ());
1062         }
1063
1064         /* Add shortcuts to special dirs */
1065         if (saved_dir) {
1066                 gtk_file_chooser_add_shortcut_folder (chooser_dialog, saved_dir, NULL);
1067         }
1068         else if (pics_dir) {
1069                 gtk_file_chooser_add_shortcut_folder (chooser_dialog, pics_dir, NULL);
1070         }
1071         if (default_dir) {
1072                 gtk_file_chooser_add_shortcut_folder (chooser_dialog, default_dir, NULL);
1073         }
1074
1075         /* Setup preview image */
1076         image = gtk_image_new ();
1077         gtk_file_chooser_set_preview_widget (chooser_dialog, image);
1078         gtk_widget_set_size_request (image, AVATAR_SIZE_SAVE, AVATAR_SIZE_SAVE);
1079         gtk_widget_show (image);
1080         gtk_file_chooser_set_use_preview_label (chooser_dialog, FALSE);
1081         g_signal_connect (chooser_dialog, "update-preview",
1082                           G_CALLBACK (avatar_chooser_update_preview_cb),
1083                           chooser);
1084
1085         /* Setup filers */
1086         filter = gtk_file_filter_new ();
1087         gtk_file_filter_set_name (filter, _("Images"));
1088         gtk_file_filter_add_pixbuf_formats (filter);
1089         gtk_file_chooser_add_filter (chooser_dialog, filter);
1090         filter = gtk_file_filter_new ();
1091         gtk_file_filter_set_name (filter, _("All Files"));
1092         gtk_file_filter_add_pattern (filter, "*");
1093         gtk_file_chooser_add_filter (chooser_dialog, filter);
1094
1095         /* Setup response */
1096         gtk_dialog_set_default_response (GTK_DIALOG (chooser_dialog), EMPATHY_AVATAR_CHOOSER_RESPONSE_FILE);
1097         g_signal_connect (chooser_dialog, "response",
1098                           G_CALLBACK (avatar_chooser_response_cb),
1099                           chooser);
1100
1101         gtk_widget_show (GTK_WIDGET (chooser_dialog));
1102
1103         g_free (saved_dir);
1104 }
1105
1106 /**
1107  * empathy_avatar_chooser_new:
1108  *
1109  * Creates a new #EmpathyAvatarChooser.
1110  *
1111  * Return value: a new #EmpathyAvatarChooser
1112  */
1113 GtkWidget *
1114 empathy_avatar_chooser_new (void)
1115 {
1116         return g_object_new (EMPATHY_TYPE_AVATAR_CHOOSER, NULL);
1117 }
1118
1119 /**
1120  * empathy_avatar_chooser_set:
1121  * @chooser: an #EmpathyAvatarChooser
1122  * @avatar: a new #EmpathyAvatar
1123  *
1124  * Sets the @chooser to display the avatar indicated by @avatar.
1125  */
1126 void
1127 empathy_avatar_chooser_set (EmpathyAvatarChooser *chooser,
1128                             EmpathyAvatar        *avatar)
1129 {
1130         g_return_if_fail (EMPATHY_IS_AVATAR_CHOOSER (chooser));
1131
1132         if (avatar != NULL) {
1133                 avatar_chooser_set_image_from_avatar (chooser, avatar, FALSE);
1134         } else {
1135                 avatar_chooser_clear_image (chooser);
1136         }
1137 }
1138
1139 /**
1140  * empathy_avatar_chooser_get_image_data:
1141  * @chooser: an #EmpathyAvatarChooser
1142  * @data: avatar bytes
1143  * @data_size: size of @data
1144  * @mime_type: avatar mime-type
1145  *
1146  * Gets image data about the currently selected avatar.
1147  */
1148 void
1149 empathy_avatar_chooser_get_image_data (EmpathyAvatarChooser  *chooser,
1150                                        const gchar          **data,
1151                                        gsize                 *data_size,
1152                                        const gchar          **mime_type)
1153 {
1154         EmpathyAvatarChooserPriv *priv;
1155
1156         g_return_if_fail (EMPATHY_IS_AVATAR_CHOOSER (chooser));
1157
1158         priv = GET_PRIV (chooser);
1159
1160         if (priv->avatar != NULL) {
1161                 if (data != NULL) {
1162                         *data = (gchar *) priv->avatar->data;
1163                 }
1164                 if (data_size != NULL) {
1165                         *data_size = priv->avatar->len;
1166                 }
1167                 if (mime_type != NULL) {
1168                         *mime_type = priv->avatar->format;
1169                 }
1170         } else {
1171                 if (data != NULL) {
1172                         *data = NULL;
1173                 }
1174                 if (data_size != NULL) {
1175                         *data_size = 0;
1176                 }
1177                 if (mime_type != NULL) {
1178                         *mime_type = NULL;
1179                 }
1180         }
1181 }
1182
1183 void
1184 empathy_avatar_chooser_set_account (EmpathyAvatarChooser *self,
1185                                        TpAccount *account)
1186 {
1187         g_return_if_fail (account != NULL);
1188
1189         avatar_chooser_set_connection (self, tp_account_get_connection (account));
1190         g_object_notify (G_OBJECT (self), "connection");
1191 }