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