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