]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-chat.c
Merge remote-tracking branch 'glassrose/moving-part-functionality-to-empathy-chat...
[empathy.git] / libempathy-gtk / empathy-chat.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  * Copyright (C) 2002-2007 Imendio AB
4  * Copyright (C) 2007-2010 Collabora Ltd.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation; either version 2 of the
9  * License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public
17  * License along with this program; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA  02110-1301  USA
20  *
21  * Authors: Mikael Hallendal <micke@imendio.com>
22  *          Richard Hult <richard@imendio.com>
23  *          Martyn Russell <martyn@imendio.com>
24  *          Geert-Jan Van den Bogaerde <geertjan@gnome.org>
25  *          Xavier Claessens <xclaesse@gmail.com>
26  */
27
28 #include <config.h>
29
30 #include <string.h>
31 #include <stdlib.h>
32
33 #undef G_DISABLE_DEPRECATED /* for GCompletion */
34 #include <gdk/gdkkeysyms.h>
35 #include <glib/gi18n-lib.h>
36 #include <gtk/gtk.h>
37
38 #include <telepathy-glib/account-manager.h>
39 #include <telepathy-glib/util.h>
40 #include <telepathy-logger/log-manager.h>
41 #include <libempathy/empathy-contact-list.h>
42 #include <libempathy/empathy-gsettings.h>
43 #include <libempathy/empathy-keyring.h>
44 #include <libempathy/empathy-utils.h>
45 #include <libempathy/empathy-request-util.h>
46 #include <libempathy/empathy-chatroom-manager.h>
47
48 #include "empathy-chat.h"
49 #include "empathy-spell.h"
50 #include "empathy-contact-list-store.h"
51 #include "empathy-contact-list-view.h"
52 #include "empathy-contact-menu.h"
53 #include "empathy-gtk-marshal.h"
54 #include "empathy-input-text-view.h"
55 #include "empathy-search-bar.h"
56 #include "empathy-theme-manager.h"
57 #include "empathy-smiley-manager.h"
58 #include "empathy-ui-utils.h"
59 #include "empathy-string-parser.h"
60 #include "extensions/extensions.h"
61
62 #define DEBUG_FLAG EMPATHY_DEBUG_CHAT
63 #include <libempathy/empathy-debug.h>
64
65 #define IS_ENTER(v) (v == GDK_KEY_Return || v == GDK_KEY_ISO_Enter || v == GDK_KEY_KP_Enter)
66 #define COMPOSING_STOP_TIMEOUT 5
67
68 #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyChat)
69 struct _EmpathyChatPriv {
70         EmpathyTpChat     *tp_chat;
71         TpAccount         *account;
72         gchar             *id;
73         gchar             *name;
74         gchar             *subject;
75         EmpathyContact    *remote_contact;
76         gboolean           show_contacts;
77
78         GSettings         *gsettings_chat;
79         GSettings         *gsettings_ui;
80
81         TplLogManager     *log_manager;
82         TpAccountManager  *account_manager;
83         GList             *input_history;
84         GList             *input_history_current;
85         GList             *compositors;
86         GCompletion       *completion;
87         guint              composing_stop_timeout_id;
88         guint              block_events_timeout_id;
89         TpHandleType       handle_type;
90         gint               contacts_width;
91         gboolean           has_input_vscroll;
92
93         /* TRUE if spell checking is enabled, FALSE otherwise.
94          * This is to keep track of the last state of spell checking
95          * when it changes. */
96         gboolean           spell_checking_enabled;
97
98         /* These store the signal handler ids for the enclosed text entry. */
99         gulong             insert_text_id;
100         gulong             delete_range_id;
101         gulong             notify_cursor_position_id;
102
103         /* Source func ID for update_misspelled_words () */
104         guint              update_misspelled_words_id;
105         /* Source func ID for save_paned_pos_timeout () */
106         guint              save_paned_pos_id;
107
108         GtkWidget         *widget;
109         GtkWidget         *hpaned;
110         GtkWidget         *vbox_left;
111         GtkWidget         *scrolled_window_chat;
112         GtkWidget         *scrolled_window_input;
113         GtkWidget         *scrolled_window_contacts;
114         GtkWidget         *hbox_topic;
115         GtkWidget         *expander_topic;
116         GtkWidget         *label_topic;
117         GtkWidget         *contact_list_view;
118         GtkWidget         *info_bar_vbox;
119         GtkWidget         *search_bar;
120
121         guint              unread_messages;
122         /* TRUE if the pending messages can be displayed. This is to avoid to show
123          * pending messages *before* messages from logs. (#603980) */
124         gboolean           can_show_pending;
125
126         /* FIXME: retrieving_backlogs flag is a workaround for Bug#610994 and should
127          * be differently handled since it introduces another race condition, which
128          * is really hard to occur, but still possible.
129          *
130          * With the current workaround (which has the race above), we need to be
131          * sure to ACK any pending messages only when the retrieval of backlogs is
132          * finished, that's why using retrieving_backlogs flag.
133          * empathy_chat_messages_read () will check this variable and not ACK
134          * anything when TRUE. It will be set TRUE at chat_constructed () and set
135          * back to FALSE when the backlog has been retrieved and the pending
136          * messages actually showed to the user.
137          *
138          * Race condition introduced with this workaround:
139          * Scenario: a message is pending, the user is notified and selects the tab.
140          * the tab with a pending message is focused before the messages are properly
141          * shown (since the preparation of the window is slower AND async WRT the
142          * tab showing), which means the user won't see any new messages (rare but
143          * possible), if he/she will change tab focus before the messages are
144          * properly shown, the tab will be set as 'seen' and the user won't be
145          * notified again about the already notified pending messages when the
146          * messages in tab will be properly shown */
147         gboolean           retrieving_backlogs;
148         gboolean           sms_channel;
149 };
150
151 typedef struct {
152         gchar *text; /* Original message that was specified
153                       * upon entry creation. */
154         gchar *modified_text; /* Message that was modified by user.
155                                * When no modifications were made, it is NULL */
156 } InputHistoryEntry;
157
158 enum {
159         COMPOSING,
160         NEW_MESSAGE,
161         PART_COMMAND_ENTERED,
162         LAST_SIGNAL
163 };
164
165 enum {
166         PROP_0,
167         PROP_TP_CHAT,
168         PROP_ACCOUNT,
169         PROP_ID,
170         PROP_NAME,
171         PROP_SUBJECT,
172         PROP_REMOTE_CONTACT,
173         PROP_SHOW_CONTACTS,
174         PROP_SMS_CHANNEL,
175         PROP_N_MESSAGES_SENDING,
176 };
177
178 static guint signals[LAST_SIGNAL] = { 0 };
179
180 G_DEFINE_TYPE (EmpathyChat, empathy_chat, GTK_TYPE_BIN);
181
182 static gboolean update_misspelled_words (gpointer data);
183
184 static void
185 chat_get_property (GObject    *object,
186                    guint       param_id,
187                    GValue     *value,
188                    GParamSpec *pspec)
189 {
190         EmpathyChat *chat = EMPATHY_CHAT (object);
191         EmpathyChatPriv *priv = GET_PRIV (object);
192
193         switch (param_id) {
194         case PROP_TP_CHAT:
195                 g_value_set_object (value, priv->tp_chat);
196                 break;
197         case PROP_ACCOUNT:
198                 g_value_set_object (value, priv->account);
199                 break;
200         case PROP_NAME:
201                 g_value_take_string (value, empathy_chat_dup_name (chat));
202                 break;
203         case PROP_ID:
204                 g_value_set_string (value, priv->id);
205                 break;
206         case PROP_SUBJECT:
207                 g_value_set_string (value, priv->subject);
208                 break;
209         case PROP_REMOTE_CONTACT:
210                 g_value_set_object (value, priv->remote_contact);
211                 break;
212         case PROP_SHOW_CONTACTS:
213                 g_value_set_boolean (value, priv->show_contacts);
214                 break;
215         case PROP_SMS_CHANNEL:
216                 g_value_set_boolean (value, priv->sms_channel);
217                 break;
218         case PROP_N_MESSAGES_SENDING:
219                 g_value_set_uint (value,
220                         empathy_chat_get_n_messages_sending (chat));
221                 break;
222         default:
223                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
224                 break;
225         };
226 }
227
228 static void
229 chat_set_property (GObject      *object,
230                    guint         param_id,
231                    const GValue *value,
232                    GParamSpec   *pspec)
233 {
234         EmpathyChat *chat = EMPATHY_CHAT (object);
235
236         switch (param_id) {
237         case PROP_TP_CHAT:
238                 empathy_chat_set_tp_chat (chat, EMPATHY_TP_CHAT (g_value_get_object (value)));
239                 break;
240         case PROP_SHOW_CONTACTS:
241                 empathy_chat_set_show_contacts (chat, g_value_get_boolean (value));
242                 break;
243         default:
244                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
245                 break;
246         };
247 }
248
249 static void
250 account_reconnected (EmpathyChat *chat,
251                         TpAccount *account)
252 {
253         EmpathyChatPriv *priv = GET_PRIV (chat);
254
255         DEBUG ("Account reconnected, request a new Text channel");
256
257         /* FIXME: Ideally we should ask to handle ourself the channel so we can
258         * report the error if any but this is blocked by
259         * https://bugs.freedesktop.org/show_bug.cgi?id=13422 */
260         switch (priv->handle_type) {
261                 case TP_HANDLE_TYPE_CONTACT:
262                         if (priv->sms_channel)
263                                 empathy_sms_contact_id (
264                                         account, priv->id,
265                                         TP_USER_ACTION_TIME_NOT_USER_ACTION);
266                         else
267                                 empathy_chat_with_contact_id (
268                                         account, priv->id,
269                                         TP_USER_ACTION_TIME_NOT_USER_ACTION);
270                         break;
271                 case TP_HANDLE_TYPE_ROOM:
272                         empathy_join_muc (account, priv->id,
273                                 TP_USER_ACTION_TIME_NOT_USER_ACTION);
274                         break;
275                 case TP_HANDLE_TYPE_NONE:
276                 case TP_HANDLE_TYPE_LIST:
277                 case TP_HANDLE_TYPE_GROUP:
278                 default:
279                         g_assert_not_reached ();
280                         break;
281         }
282
283         g_object_unref (chat);
284 }
285
286 static void
287 chat_new_connection_cb (TpAccount   *account,
288                         guint        old_status,
289                         guint        new_status,
290                         guint        reason,
291                         gchar       *dbus_error_name,
292                         GHashTable  *details,
293                         EmpathyChat *chat)
294 {
295         EmpathyChatPriv *priv = GET_PRIV (chat);
296
297         if (new_status != TP_CONNECTION_STATUS_CONNECTED)
298                 return;
299
300         if (priv->tp_chat != NULL || account != priv->account ||
301             priv->handle_type == TP_HANDLE_TYPE_NONE ||
302             EMP_STR_EMPTY (priv->id))
303                 return;
304
305         g_object_ref (chat);
306
307         account_reconnected (chat, account);
308 }
309
310 static void
311 chat_composing_remove_timeout (EmpathyChat *chat)
312 {
313         EmpathyChatPriv *priv;
314
315         priv = GET_PRIV (chat);
316
317         if (priv->composing_stop_timeout_id) {
318                 g_source_remove (priv->composing_stop_timeout_id);
319                 priv->composing_stop_timeout_id = 0;
320         }
321 }
322
323 static gboolean
324 chat_composing_stop_timeout_cb (EmpathyChat *chat)
325 {
326         EmpathyChatPriv *priv;
327
328         priv = GET_PRIV (chat);
329
330         priv->composing_stop_timeout_id = 0;
331         empathy_tp_chat_set_state (priv->tp_chat,
332                                    TP_CHANNEL_CHAT_STATE_PAUSED);
333
334         return FALSE;
335 }
336
337 static void
338 chat_composing_start (EmpathyChat *chat)
339 {
340         EmpathyChatPriv *priv;
341
342         priv = GET_PRIV (chat);
343
344         if (priv->composing_stop_timeout_id) {
345                 /* Just restart the timeout */
346                 chat_composing_remove_timeout (chat);
347         } else {
348                 empathy_tp_chat_set_state (priv->tp_chat,
349                                            TP_CHANNEL_CHAT_STATE_COMPOSING);
350         }
351
352         priv->composing_stop_timeout_id = g_timeout_add_seconds (
353                 COMPOSING_STOP_TIMEOUT,
354                 (GSourceFunc) chat_composing_stop_timeout_cb,
355                 chat);
356 }
357
358 static void
359 chat_composing_stop (EmpathyChat *chat)
360 {
361         EmpathyChatPriv *priv;
362
363         priv = GET_PRIV (chat);
364
365         chat_composing_remove_timeout (chat);
366         empathy_tp_chat_set_state (priv->tp_chat,
367                                    TP_CHANNEL_CHAT_STATE_ACTIVE);
368 }
369
370 static gint
371 chat_input_history_entry_cmp (InputHistoryEntry *entry,
372                               const gchar *text)
373 {
374         if (!tp_strdiff (entry->text, text)) {
375                 if (entry->modified_text != NULL) {
376                         /* Modified entry and single string cannot be equal. */
377                         return 1;
378                 }
379                 return 0;
380         }
381         return 1;
382 }
383
384 static InputHistoryEntry *
385 chat_input_history_entry_new_with_text (const gchar *text)
386 {
387         InputHistoryEntry *entry;
388         entry = g_slice_new0 (InputHistoryEntry);
389         entry->text = g_strdup (text);
390
391         return entry;
392 }
393
394 static void
395 chat_input_history_entry_free (InputHistoryEntry *entry)
396 {
397         g_free (entry->text);
398         g_free (entry->modified_text);
399         g_slice_free (InputHistoryEntry, entry);
400 }
401
402 static void
403 chat_input_history_entry_revert (InputHistoryEntry *entry)
404 {
405         g_free (entry->modified_text);
406         entry->modified_text = NULL;
407 }
408
409 static void
410 chat_input_history_entry_update_text (InputHistoryEntry *entry,
411                                       const gchar *text)
412 {
413         gchar *old;
414
415         if (!tp_strdiff (text, entry->text)) {
416                 g_free (entry->modified_text);
417                 entry->modified_text = NULL;
418                 return;
419         }
420
421         old = entry->modified_text;
422         entry->modified_text = g_strdup (text);
423         g_free (old);
424 }
425
426 static const gchar *
427 chat_input_history_entry_get_text (InputHistoryEntry *entry)
428 {
429         if (entry == NULL) {
430                 return NULL;
431         }
432
433         if (entry->modified_text != NULL) {
434                 return entry->modified_text;
435         }
436         return entry->text;
437 }
438
439 static GList *
440 chat_input_history_remove_item (GList *list,
441                                 GList *item)
442 {
443         list = g_list_remove_link (list, item);
444         chat_input_history_entry_free (item->data);
445         g_list_free_1 (item);
446         return list;
447 }
448
449 static void
450 chat_input_history_revert (EmpathyChat *chat)
451 {
452         EmpathyChatPriv   *priv;
453         GList             *list;
454         GList             *item1;
455         GList             *item2;
456         InputHistoryEntry *entry;
457
458         priv = GET_PRIV (chat);
459         list = priv->input_history;
460
461         if (list == NULL) {
462                 DEBUG ("No input history");
463                 return;
464         }
465
466         /* Delete temporary entry */
467         if (priv->input_history_current != NULL) {
468                 item1 = list;
469                 list = chat_input_history_remove_item (list, item1);
470                 if (priv->input_history_current == item1) {
471                         /* Removed temporary entry was current entry */
472                         priv->input_history = list;
473                         priv->input_history_current = NULL;
474                         return;
475                 }
476         }
477         else {
478                 /* There is no entry to revert */
479                 return;
480         }
481
482         /* Restore the current history entry to original value */
483         item1 = priv->input_history_current;
484         entry = item1->data;
485         chat_input_history_entry_revert (entry);
486
487         /* Remove restored entry if there is other occurance before this entry */
488         item2 = g_list_find_custom (list, chat_input_history_entry_get_text (entry),
489                                     (GCompareFunc) chat_input_history_entry_cmp);
490         if (item2 != item1) {
491                 list = chat_input_history_remove_item (list, item1);
492         }
493         else {
494                 /* Remove other occurance of the restored entry */
495                 item2 = g_list_find_custom (item1->next,
496                                             chat_input_history_entry_get_text (entry),
497                                             (GCompareFunc) chat_input_history_entry_cmp);
498                 if (item2 != NULL) {
499                         list = chat_input_history_remove_item (list, item2);
500                 }
501         }
502
503         priv->input_history_current = NULL;
504         priv->input_history = list;
505 }
506
507 static void
508 chat_input_history_add (EmpathyChat  *chat,
509                         const gchar *str,
510                         gboolean temporary)
511 {
512         EmpathyChatPriv   *priv;
513         GList             *list;
514         GList             *item;
515         InputHistoryEntry *entry;
516
517         priv = GET_PRIV (chat);
518
519         list = priv->input_history;
520
521         /* Remove any other occurances of this entry, if not temporary */
522         if (!temporary) {
523                 while ((item = g_list_find_custom (list, str,
524                     (GCompareFunc) chat_input_history_entry_cmp)) != NULL) {
525                         list = chat_input_history_remove_item (list, item);
526                 }
527
528                 /* Trim the list to the last 10 items */
529                 while (g_list_length (list) > 10) {
530                         item = g_list_last (list);
531                         if (item != NULL) {
532                                 list = chat_input_history_remove_item (list, item);
533                         }
534                 }
535         }
536
537
538
539         /* Add new entry */
540         entry = chat_input_history_entry_new_with_text (str);
541         list = g_list_prepend (list, entry);
542
543         /* Set the list and the current item pointer */
544         priv->input_history = list;
545         if (temporary) {
546                 priv->input_history_current = list;
547         }
548         else {
549                 priv->input_history_current = NULL;
550         }
551 }
552
553 static const gchar *
554 chat_input_history_get_next (EmpathyChat *chat)
555 {
556         EmpathyChatPriv *priv;
557         GList           *item;
558         const gchar     *msg;
559
560         priv = GET_PRIV (chat);
561
562         if (priv->input_history == NULL) {
563                 DEBUG ("No input history, next entry is NULL");
564                 return NULL;
565         }
566         g_assert (priv->input_history_current != NULL);
567
568         if ((item = g_list_next (priv->input_history_current)) == NULL)
569         {
570                 item = priv->input_history_current;
571         }
572
573         msg = chat_input_history_entry_get_text (item->data);
574
575         DEBUG ("Returning next entry: '%s'", msg);
576
577         priv->input_history_current = item;
578
579         return msg;
580 }
581
582 static const gchar *
583 chat_input_history_get_prev (EmpathyChat *chat)
584 {
585         EmpathyChatPriv *priv;
586         GList           *item;
587         const gchar     *msg;
588
589         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
590
591         priv = GET_PRIV (chat);
592
593         if (priv->input_history == NULL) {
594                 DEBUG ("No input history, previous entry is NULL");
595                 return NULL;
596         }
597
598         if (priv->input_history_current == NULL)
599         {
600                 return NULL;
601         }
602         else if ((item = g_list_previous (priv->input_history_current)) == NULL)
603         {
604                 item = priv->input_history_current;
605         }
606
607         msg = chat_input_history_entry_get_text (item->data);
608
609         DEBUG ("Returning previous entry: '%s'", msg);
610
611         priv->input_history_current = item;
612
613         return msg;
614 }
615
616 static void
617 chat_input_history_update (EmpathyChat *chat,
618                            GtkTextBuffer *buffer)
619 {
620         EmpathyChatPriv      *priv;
621         GtkTextIter           start, end;
622         gchar                *text;
623         InputHistoryEntry    *entry;
624
625         priv = GET_PRIV (chat);
626
627         gtk_text_buffer_get_bounds (buffer, &start, &end);
628         text = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
629
630         if (priv->input_history_current == NULL) {
631                 /* Add the current text temporarily to the history */
632                 chat_input_history_add (chat, text, TRUE);
633                 g_free (text);
634                 return;
635         }
636
637         /* Save the changes in the history */
638         entry = priv->input_history_current->data;
639         if (tp_strdiff (chat_input_history_entry_get_text (entry), text)) {
640                 chat_input_history_entry_update_text (entry, text);
641         }
642
643         g_free (text);
644 }
645
646 typedef struct {
647         EmpathyChat *chat;
648         gchar *message;
649 } ChatCommandMsgData;
650
651 static void
652 chat_command_msg_cb (GObject *source,
653                               GAsyncResult *result,
654                               gpointer                  user_data)
655 {
656         ChatCommandMsgData *data = user_data;
657         GError *error = NULL;
658         TpChannel *channel;
659
660         channel = tp_account_channel_request_ensure_and_observe_channel_finish (
661                                         TP_ACCOUNT_CHANNEL_REQUEST (source), result, &error);
662
663         if (channel == NULL) {
664                 DEBUG ("Failed to get channel: %s", error->message);
665                 g_error_free (error);
666
667                 empathy_chat_view_append_event (data->chat->view,
668                         _("Failed to open private chat"));
669                 goto OUT;
670         }
671
672         if (!EMP_STR_EMPTY (data->message) && TP_IS_TEXT_CHANNEL (channel)) {
673                 TpTextChannel *text = (TpTextChannel *) channel;
674                 TpMessage *msg;
675
676                 msg = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,
677                         data->message);
678
679                 tp_text_channel_send_message_async (text, msg, 0, NULL, NULL);
680
681                 g_object_unref (msg);
682         }
683
684         g_object_unref (channel);
685
686 OUT:
687         g_free (data->message);
688         g_slice_free (ChatCommandMsgData, data);
689 }
690
691 static gboolean
692 nick_command_supported (EmpathyChat *chat)
693 {
694         EmpathyChatPriv * priv = GET_PRIV (chat);
695         TpConnection    *connection;
696
697         connection = empathy_tp_chat_get_connection (priv->tp_chat);
698         return tp_proxy_has_interface_by_id (connection,
699                 EMP_IFACE_QUARK_CONNECTION_INTERFACE_RENAMING);
700 }
701
702 static gboolean
703 part_command_supported (EmpathyChat *chat)
704 {
705         EmpathyChatPriv * priv = GET_PRIV (chat);
706         TpChannel *channel;
707
708         channel = empathy_tp_chat_get_channel (priv->tp_chat);
709         return tp_proxy_has_interface_by_id (channel,
710                         TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP);
711 }
712
713 static void
714 chat_command_clear (EmpathyChat *chat,
715                     GStrv        strv)
716 {
717         empathy_chat_view_clear (chat->view);
718 }
719
720 static void
721 chat_command_topic (EmpathyChat *chat,
722                     GStrv        strv)
723 {
724         EmpathyChatPriv *priv = GET_PRIV (chat);
725         EmpathyTpChatProperty *property;
726         GValue value = {0, };
727
728         property = empathy_tp_chat_get_property (priv->tp_chat, "subject");
729         if (property == NULL) {
730                 empathy_chat_view_append_event (chat->view,
731                         _("Topic not supported on this conversation"));
732                 return;
733         }
734
735         if (!(property->flags & TP_PROPERTY_FLAG_WRITE)) {
736                 empathy_chat_view_append_event (chat->view,
737                         _("You are not allowed to change the topic"));
738                 return;
739         }
740
741         g_value_init (&value, G_TYPE_STRING);
742         g_value_set_string (&value, strv[1]);
743         empathy_tp_chat_set_property (priv->tp_chat, "subject", &value);
744         g_value_unset (&value);
745 }
746
747 void
748 empathy_chat_join_muc (EmpathyChat *chat,
749                    const gchar   *room)
750 {
751         EmpathyChatPriv *priv = GET_PRIV (chat);
752
753         empathy_join_muc (priv->account, room,
754                 empathy_get_current_action_time ());
755 }
756
757 static void
758 chat_command_join (EmpathyChat *chat,
759                    GStrv        strv)
760 {
761         guint i = 0;
762
763         GStrv rooms = g_strsplit_set (strv[1], ", ", -1);
764
765         /* FIXME: Ideally we should ask to handle ourself the channel so we can
766         * report the error if any but this is blocked by
767         * https://bugs.freedesktop.org/show_bug.cgi?id=13422 */
768         while (rooms[i] != NULL) {
769                 /* ignore empty strings */
770                 if (!EMP_STR_EMPTY (rooms[i])) {
771                         empathy_chat_join_muc (chat, rooms[i]);
772                 }
773                 i++;
774         }
775         g_strfreev (rooms);
776 }
777
778 static void
779 chat_command_part (EmpathyChat *chat,
780                            GStrv        strv)
781 {
782         g_signal_emit (chat, signals[PART_COMMAND_ENTERED], 0, strv);
783 }
784
785 static void
786 chat_command_msg_internal (EmpathyChat *chat,
787                            const gchar *contact_id,
788                            const gchar *message)
789 {
790         EmpathyChatPriv *priv = GET_PRIV (chat);
791         ChatCommandMsgData *data;
792         TpAccountChannelRequest *req;
793         GHashTable *request;
794
795         request = tp_asv_new (
796                 TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING, TP_IFACE_CHANNEL_TYPE_TEXT,
797                 TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT, TP_HANDLE_TYPE_CONTACT,
798                 TP_PROP_CHANNEL_TARGET_ID, G_TYPE_STRING, contact_id,
799                 NULL);
800
801         req = tp_account_channel_request_new (priv->account, request,
802                 empathy_get_current_action_time ());
803
804         /* FIXME: We should probably search in members alias. But this
805          * is enough for IRC */
806         data = g_slice_new (ChatCommandMsgData);
807         data->chat = chat;
808         data->message = g_strdup (message);
809
810         tp_account_channel_request_ensure_and_observe_channel_async (req,
811                 EMPATHY_CHAT_BUS_NAME, NULL, chat_command_msg_cb, data);
812
813         g_object_unref (req);
814         g_hash_table_unref (request);
815 }
816
817 static void
818 chat_command_query (EmpathyChat *chat,
819                     GStrv        strv)
820 {
821         /* If <message> part is not defined,
822          * strv[2] will be the terminal NULL */
823         chat_command_msg_internal (chat, strv[1], strv[2]);
824 }
825
826 static void
827 chat_command_msg (EmpathyChat *chat,
828                   GStrv        strv)
829 {
830         chat_command_msg_internal (chat, strv[1], strv[2]);
831 }
832
833 static void
834 callback_for_request_rename (TpProxy *proxy,
835                   const GError *error,
836                   gpointer user_data,
837                   GObject *weak_object)
838 {
839         if (error != NULL) {
840                 DEBUG ("Call to RequestRename method failed: %s",error->message);
841         }
842 }
843
844 static void
845 chat_command_nick (EmpathyChat *chat,
846                    GStrv        strv)
847 {
848         EmpathyChatPriv *priv = GET_PRIV (chat);
849         TpProxy *proxy;
850
851         proxy = TP_PROXY (tp_account_get_connection (priv->account));
852
853         emp_cli_connection_interface_renaming_call_request_rename (proxy, -1,
854                 strv[1], callback_for_request_rename, NULL, NULL, NULL);
855 }
856
857 static void
858 chat_command_me (EmpathyChat *chat,
859                   GStrv        strv)
860 {
861         EmpathyChatPriv *priv = GET_PRIV (chat);
862         TpMessage *message;
863         TpChannel *channel;
864
865         channel = empathy_tp_chat_get_channel (priv->tp_chat);
866
867         /* Strictly speaking we don't depend yet on Messages so best to check that
868          * the channel is actually a TpTextChannel before casting it. */
869         if (TP_IS_TEXT_CHANNEL (channel) &&
870                 !tp_text_channel_supports_message_type (TP_TEXT_CHANNEL (channel),
871                         TP_CHANNEL_TEXT_MESSAGE_TYPE_ACTION)) {
872                 /* Action message are not supported, 'simulate' the action */
873                 EmpathyContact *self_contact;
874                 gchar *tmp;
875
876                 self_contact = empathy_tp_chat_get_self_contact (priv->tp_chat);
877                 /* The TpChat can't be ready if it doesn't have the self contact */
878                 g_assert (self_contact != NULL);
879
880                 tmp = g_strdup_printf ("%s %s", empathy_contact_get_alias (self_contact),
881                         strv[1]);
882                 message = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,
883                         tmp);
884                 g_free (tmp);
885         }
886         else {
887                 message = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_ACTION,
888                         strv[1]);
889         }
890
891         empathy_tp_chat_send (priv->tp_chat, message);
892         g_object_unref (message);
893 }
894
895 static void
896 chat_command_say (EmpathyChat *chat,
897                   GStrv        strv)
898 {
899         EmpathyChatPriv *priv = GET_PRIV (chat);
900         TpMessage *message;
901
902         message = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,
903                 strv[1]);
904         empathy_tp_chat_send (priv->tp_chat, message);
905         g_object_unref (message);
906 }
907
908 static void chat_command_help (EmpathyChat *chat, GStrv strv);
909
910 typedef void (*ChatCommandFunc) (EmpathyChat *chat, GStrv strv);
911
912 typedef struct {
913         const gchar *prefix;
914         guint min_parts;
915         guint max_parts;
916         ChatCommandFunc func;
917         gboolean (*is_supported)(EmpathyChat *chat);
918         const gchar *help;
919 } ChatCommandItem;
920
921 static ChatCommandItem commands[] = {
922         {"clear", 1, 1, chat_command_clear, NULL,
923          N_("/clear: clear all messages from the current conversation")},
924
925         {"topic", 2, 2, chat_command_topic, NULL,
926          N_("/topic <topic>: set the topic of the current conversation")},
927
928         {"join", 2, 2, chat_command_join, NULL,
929          N_("/join <chat room ID>: join a new chat room")},
930
931         {"j", 2, 2, chat_command_join, NULL,
932          N_("/j <chat room ID>: join a new chat room")},
933
934         /* FIXME: https://bugzilla.gnome.org/show_bug.cgi?id=643295 */
935         {"part", 1, 3, chat_command_part, part_command_supported,
936          N_("/part [<chat room ID>] [<reason>]: leave the chat room, "
937             "by default the current one")},
938
939         {"query", 2, 3, chat_command_query, NULL,
940          N_("/query <contact ID> [<message>]: open a private chat")},
941
942         {"msg", 3, 3, chat_command_msg, NULL,
943          N_("/msg <contact ID> <message>: open a private chat")},
944
945         {"nick", 2, 2, chat_command_nick, nick_command_supported,
946          N_("/nick <nickname>: change your nickname on the current server")},
947
948         {"me", 2, 2, chat_command_me, NULL,
949          N_("/me <message>: send an ACTION message to the current conversation")},
950
951         {"say", 2, 2, chat_command_say, NULL,
952          N_("/say <message>: send <message> to the current conversation. "
953             "This is used to send a message starting with a '/'. For example: "
954             "\"/say /join is used to join a new chat room\"")},
955
956         {"help", 1, 2, chat_command_help, NULL,
957          N_("/help [<command>]: show all supported commands. "
958             "If <command> is defined, show its usage.")},
959 };
960
961 static void
962 chat_command_show_help (EmpathyChat     *chat,
963                         ChatCommandItem *item)
964 {
965         gchar *str;
966
967         str = g_strdup_printf (_("Usage: %s"), _(item->help));
968         empathy_chat_view_append_event (chat->view, str);
969         g_free (str);
970 }
971
972 static void
973 chat_command_help (EmpathyChat *chat,
974                    GStrv        strv)
975 {
976         guint i;
977
978         /* If <command> part is not defined,
979          * strv[1] will be the terminal NULL */
980         if (strv[1] == NULL) {
981                 for (i = 0; i < G_N_ELEMENTS (commands); i++) {
982                         if (commands[i].is_supported != NULL) {
983                                 if (!commands[i].is_supported (chat)) {
984                                         continue;
985                                 }
986                         }
987                     empathy_chat_view_append_event (chat->view,
988                             _(commands[i].help));
989                 }
990                 return;
991         }
992
993         for (i = 0; i < G_N_ELEMENTS (commands); i++) {
994                 if (g_ascii_strcasecmp (strv[1], commands[i].prefix) == 0) {
995                         if (commands[i].is_supported != NULL) {
996                                 if (!commands[i].is_supported (chat)) {
997                                         break;
998                                 }
999                         }
1000                         chat_command_show_help (chat, &commands[i]);
1001                         return;
1002                 }
1003         }
1004
1005         empathy_chat_view_append_event (chat->view,
1006                 _("Unknown command"));
1007 }
1008
1009 static GStrv
1010 chat_command_parse (const gchar *text, guint max_parts)
1011 {
1012         GPtrArray *array;
1013         gchar *item;
1014
1015         DEBUG ("Parse command, parts=%d text=\"%s\":", max_parts, text);
1016
1017         array = g_ptr_array_sized_new (max_parts + 1);
1018         while (max_parts > 1) {
1019                 const gchar *end;
1020
1021                 /* Skip white spaces */
1022                 while (g_ascii_isspace (*text)) {
1023                         text++;
1024                 }
1025
1026                 /* Search the end of this part, until first space. */
1027                 for (end = text; *end != '\0' && !g_ascii_isspace (*end); end++)
1028                         /* Do nothing */;
1029                 if (*end == '\0') {
1030                         break;
1031                 }
1032
1033                 item = g_strndup (text, end - text);
1034                 g_ptr_array_add (array, item);
1035                 DEBUG ("\tITEM: \"%s\"", item);
1036
1037                 text = end;
1038                 max_parts--;
1039         }
1040
1041         /* Append last part if not empty */
1042         item = g_strstrip (g_strdup (text));
1043         if (!EMP_STR_EMPTY (item)) {
1044                 g_ptr_array_add (array, item);
1045                 DEBUG ("\tITEM: \"%s\"", item);
1046         } else {
1047                 g_free (item);
1048         }
1049
1050         /* Make the array NULL-terminated */
1051         g_ptr_array_add (array, NULL);
1052
1053         return (GStrv) g_ptr_array_free (array, FALSE);
1054 }
1055
1056 static gboolean
1057 has_prefix_case (const gchar *s,
1058                   const gchar *prefix)
1059 {
1060         return g_ascii_strncasecmp (s, prefix, strlen (prefix)) == 0;
1061 }
1062
1063 static void
1064 chat_send (EmpathyChat  *chat,
1065            const gchar *msg)
1066 {
1067         EmpathyChatPriv *priv;
1068         TpMessage  *message;
1069         guint            i;
1070
1071         if (EMP_STR_EMPTY (msg)) {
1072                 return;
1073         }
1074
1075         priv = GET_PRIV (chat);
1076
1077         chat_input_history_add (chat, msg, FALSE);
1078
1079         if (msg[0] == '/') {
1080                 gboolean second_slash = FALSE;
1081                 const gchar *iter = msg + 1;
1082
1083                 for (i = 0; i < G_N_ELEMENTS (commands); i++) {
1084                         GStrv strv;
1085                         guint strv_len;
1086                         gchar c;
1087
1088                         if (!has_prefix_case (msg + 1, commands[i].prefix)) {
1089                                 continue;
1090                         }
1091                         c = *(msg + 1 + strlen (commands[i].prefix));
1092                         if (c != '\0' && !g_ascii_isspace (c)) {
1093                                 continue;
1094                         }
1095                         if (commands[i].is_supported != NULL) {
1096                                 if (!commands[i].is_supported (chat)) {
1097                                         continue;
1098                                 }
1099                         }
1100
1101                         /* We can't use g_strsplit here because it does
1102                          * not deal correctly if we have more than one space
1103                          * between args */
1104                         strv = chat_command_parse (msg + 1, commands[i].max_parts);
1105
1106                         strv_len = g_strv_length (strv);
1107                         if (strv_len < commands[i].min_parts ||
1108                             strv_len > commands[i].max_parts) {
1109                                 chat_command_show_help (chat, &commands[i]);
1110                                 g_strfreev (strv);
1111                                 return;
1112                         }
1113
1114                         commands[i].func (chat, strv);
1115                         g_strfreev (strv);
1116                         return;
1117                 }
1118
1119                 /* Also allow messages with two slashes before the
1120                  * first space, so it is possible to send a /unix/path.
1121                  * This heuristic is kind of crap. */
1122                 while (*iter != '\0' && !g_ascii_isspace (*iter)) {
1123                         if (*iter == '/') {
1124                                 second_slash = TRUE;
1125                                 break;
1126                         }
1127                         iter++;
1128                 }
1129
1130                 if (!second_slash) {
1131                         empathy_chat_view_append_event (chat->view,
1132                                 _("Unknown command; see /help for the available"
1133                                   " commands"));
1134                         return;
1135                 }
1136         }
1137
1138         message = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,
1139                 msg);
1140         empathy_tp_chat_send (priv->tp_chat, message);
1141         g_object_unref (message);
1142 }
1143
1144 static void
1145 chat_input_text_view_send (EmpathyChat *chat)
1146 {
1147         GtkTextBuffer  *buffer;
1148         GtkTextIter     start, end;
1149         gchar          *msg;
1150
1151         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1152
1153         gtk_text_buffer_get_bounds (buffer, &start, &end);
1154         msg = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1155
1156         /* clear the input field */
1157         gtk_text_buffer_set_text (buffer, "", -1);
1158         /* delete input history modifications */
1159         chat_input_history_revert (chat);
1160
1161         chat_send (chat, msg);
1162         g_free (msg);
1163 }
1164
1165 static void
1166 chat_state_changed_cb (EmpathyTpChat      *tp_chat,
1167                        EmpathyContact     *contact,
1168                        TpChannelChatState  state,
1169                        EmpathyChat        *chat)
1170 {
1171         EmpathyChatPriv *priv;
1172         GList          *l;
1173         gboolean        was_composing;
1174
1175         priv = GET_PRIV (chat);
1176
1177         if (empathy_contact_is_user (contact)) {
1178                 /* We don't care about our own chat state */
1179                 return;
1180         }
1181
1182         was_composing = (priv->compositors != NULL);
1183
1184         /* Find the contact in the list. After that l is the list elem or NULL */
1185         for (l = priv->compositors; l; l = l->next) {
1186                 if (contact == l->data) {
1187                         break;
1188                 }
1189         }
1190
1191         switch (state) {
1192         case TP_CHANNEL_CHAT_STATE_GONE:
1193         case TP_CHANNEL_CHAT_STATE_INACTIVE:
1194         case TP_CHANNEL_CHAT_STATE_PAUSED:
1195         case TP_CHANNEL_CHAT_STATE_ACTIVE:
1196                 /* Contact is not composing */
1197                 if (l) {
1198                         priv->compositors = g_list_remove_link (priv->compositors, l);
1199                         g_object_unref (l->data);
1200                         g_list_free1 (l);
1201                 }
1202                 break;
1203         case TP_CHANNEL_CHAT_STATE_COMPOSING:
1204                 /* Contact is composing */
1205                 if (!l) {
1206                         priv->compositors = g_list_prepend (priv->compositors,
1207                                                             g_object_ref (contact));
1208                 }
1209                 break;
1210         default:
1211                 g_assert_not_reached ();
1212         }
1213
1214         DEBUG ("Was composing: %s now composing: %s",
1215                 was_composing ? "yes" : "no",
1216                 priv->compositors ? "yes" : "no");
1217
1218         if ((was_composing && !priv->compositors) ||
1219             (!was_composing && priv->compositors)) {
1220                 /* Composing state changed */
1221                 g_signal_emit (chat, signals[COMPOSING], 0,
1222                                priv->compositors != NULL);
1223         }
1224 }
1225
1226 static void
1227 chat_message_received (EmpathyChat *chat,
1228         EmpathyMessage *message,
1229         gboolean pending)
1230 {
1231         EmpathyChatPriv *priv = GET_PRIV (chat);
1232         EmpathyContact  *sender;
1233
1234         sender = empathy_message_get_sender (message);
1235
1236         DEBUG ("Appending new message from %s (%d)",
1237                 empathy_contact_get_alias (sender),
1238                 empathy_contact_get_handle (sender));
1239
1240         empathy_chat_view_append_message (chat->view, message);
1241
1242         /* We received a message so the contact is no longer composing */
1243         chat_state_changed_cb (priv->tp_chat, sender,
1244                                TP_CHANNEL_CHAT_STATE_ACTIVE,
1245                                chat);
1246
1247         priv->unread_messages++;
1248         g_signal_emit (chat, signals[NEW_MESSAGE], 0, message, pending);
1249 }
1250
1251 static void
1252 chat_message_received_cb (EmpathyTpChat  *tp_chat,
1253                           EmpathyMessage *message,
1254                           EmpathyChat    *chat)
1255 {
1256         chat_message_received (chat, message, FALSE);
1257 }
1258
1259 static void
1260 chat_send_error_cb (EmpathyTpChat          *tp_chat,
1261                     const gchar            *message_body,
1262                     TpChannelTextSendError  error_code,
1263                     const gchar            *dbus_error,
1264                     EmpathyChat            *chat)
1265 {
1266         const gchar *error = NULL;
1267         gchar       *str;
1268
1269         if (!tp_strdiff (dbus_error, TP_ERROR_STR_INSUFFICIENT_BALANCE)) {
1270                 /* translators: error used when user doesn't have enough credit on his
1271                  * account to send the message. */
1272                 error = _("insufficient balance to send message");
1273         } else if (!tp_strdiff (dbus_error, TP_ERROR_STR_NOT_CAPABLE)) {
1274                 error = _("not capable");
1275         }
1276
1277         if (error == NULL) {
1278                 /* if we didn't find a dbus-error, try the old error */
1279                 switch (error_code) {
1280                 case TP_CHANNEL_TEXT_SEND_ERROR_OFFLINE:
1281                         error = _("offline");
1282                         break;
1283                 case TP_CHANNEL_TEXT_SEND_ERROR_INVALID_CONTACT:
1284                         error = _("invalid contact");
1285                         break;
1286                 case TP_CHANNEL_TEXT_SEND_ERROR_PERMISSION_DENIED:
1287                         error = _("permission denied");
1288                         break;
1289                 case TP_CHANNEL_TEXT_SEND_ERROR_TOO_LONG:
1290                         error = _("too long message");
1291                         break;
1292                 case TP_CHANNEL_TEXT_SEND_ERROR_NOT_IMPLEMENTED:
1293                         error = _("not implemented");
1294                         break;
1295                 case TP_CHANNEL_TEXT_SEND_ERROR_UNKNOWN:
1296                 default:
1297                         error = _("unknown");
1298                         break;
1299                 }
1300         }
1301
1302         if (message_body != NULL) {
1303                         str = g_strdup_printf (_("Error sending message '%s': %s"),
1304                                 message_body, error);
1305         }
1306         else {
1307                         str = g_strdup_printf (_("Error sending message: %s"), error);
1308         }
1309
1310         empathy_chat_view_append_event (chat->view, str);
1311         g_free (str);
1312 }
1313
1314 static void
1315 chat_topic_label_size_allocate_cb (GtkLabel *label,
1316                                    GtkAllocation *allocation,
1317                                    EmpathyChat *chat)
1318 {
1319         EmpathyChatPriv *priv = GET_PRIV (chat);
1320
1321         if (!gtk_label_get_line_wrap (label)) {
1322                 if (pango_layout_is_ellipsized (gtk_label_get_layout (label)))
1323                         gtk_widget_show (priv->expander_topic);
1324                 else
1325                         gtk_widget_hide (priv->expander_topic);
1326
1327                 return;
1328         }
1329 }
1330
1331 static void
1332 chat_topic_expander_activate_cb (GtkExpander *expander,
1333                                  GParamSpec *param_spec,
1334                                  EmpathyChat *chat)
1335 {
1336         EmpathyChatPriv *priv = GET_PRIV (chat);
1337
1338         if (gtk_expander_get_expanded (expander)) {
1339                 gtk_label_set_ellipsize (GTK_LABEL (priv->label_topic), PANGO_ELLIPSIZE_NONE);
1340                 gtk_label_set_line_wrap (GTK_LABEL (priv->label_topic), TRUE);
1341         } else {
1342                 gtk_label_set_ellipsize (GTK_LABEL (priv->label_topic), PANGO_ELLIPSIZE_END);
1343                 gtk_label_set_line_wrap (GTK_LABEL (priv->label_topic), FALSE);
1344         }
1345 }
1346
1347 static void
1348 chat_property_changed_cb (EmpathyTpChat *tp_chat,
1349                           const gchar   *name,
1350                           GValue        *value,
1351                           EmpathyChat   *chat)
1352 {
1353         EmpathyChatPriv *priv = GET_PRIV (chat);
1354
1355         if (!tp_strdiff (name, "subject")) {
1356                 g_free (priv->subject);
1357                 priv->subject = g_value_dup_string (value);
1358                 g_object_notify (G_OBJECT (chat), "subject");
1359
1360                 if (EMP_STR_EMPTY (priv->subject)) {
1361                         gtk_widget_hide (priv->hbox_topic);
1362                 } else {
1363                         gchar *markup_topic;
1364                         gchar *markup_text;
1365
1366                         markup_topic = empathy_add_link_markup (priv->subject);
1367                         markup_text = g_strdup_printf ("<span weight=\"bold\">%s</span> %s",
1368                                 _("Topic:"), markup_topic);
1369
1370                         gtk_label_set_markup (GTK_LABEL (priv->label_topic), markup_text);
1371                         g_free (markup_text);
1372                         g_free (markup_topic);
1373
1374                         gtk_widget_show (priv->hbox_topic);
1375                 }
1376                 if (priv->block_events_timeout_id == 0) {
1377                         gchar *str;
1378
1379                         if (!EMP_STR_EMPTY (priv->subject)) {
1380                                 str = g_strdup_printf (_("Topic set to: %s"), priv->subject);
1381                         } else {
1382                                 str = g_strdup (_("No topic defined"));
1383                         }
1384                         empathy_chat_view_append_event (EMPATHY_CHAT (chat)->view, str);
1385                         g_free (str);
1386                 }
1387         }
1388         else if (!tp_strdiff (name, "name")) {
1389                 g_free (priv->name);
1390                 priv->name = g_value_dup_string (value);
1391                 g_object_notify (G_OBJECT (chat), "name");
1392         }
1393 }
1394
1395 static gboolean
1396 chat_input_text_get_word_from_iter (GtkTextIter   *iter,
1397                                     GtkTextIter   *start,
1398                                     GtkTextIter   *end)
1399 {
1400         GtkTextIter word_start = *iter;
1401         GtkTextIter word_end = *iter;
1402         GtkTextIter tmp;
1403
1404         if (gtk_text_iter_inside_word (&word_end) &&
1405                         !gtk_text_iter_ends_word (&word_end)) {
1406                 gtk_text_iter_forward_word_end (&word_end);
1407         }
1408
1409         tmp = word_end;
1410
1411         if (gtk_text_iter_get_char (&tmp) == '\'') {
1412                 gtk_text_iter_forward_char (&tmp);
1413
1414                 if (g_unichar_isalpha (gtk_text_iter_get_char (&tmp))) {
1415                         gtk_text_iter_forward_word_end (&word_end);
1416                 }
1417         }
1418
1419
1420         if (gtk_text_iter_inside_word (&word_start) ||
1421                         gtk_text_iter_ends_word (&word_start)) {
1422                 if (!gtk_text_iter_starts_word (&word_start) ||
1423                                 gtk_text_iter_equal (&word_start, &word_end)) {
1424                         gtk_text_iter_backward_word_start (&word_start);
1425                 }
1426
1427                 tmp = word_start;
1428                 gtk_text_iter_backward_char (&tmp);
1429
1430                 if (gtk_text_iter_get_char (&tmp) == '\'') {
1431                         gtk_text_iter_backward_char (&tmp);
1432
1433                         if (g_unichar_isalpha (gtk_text_iter_get_char (&tmp))) {
1434                                 gtk_text_iter_backward_word_start (&word_start);
1435                         }
1436                 }
1437         }
1438
1439         *start = word_start;
1440         *end = word_end;
1441         return TRUE;
1442 }
1443
1444 static void
1445 chat_input_text_buffer_insert_text_cb (GtkTextBuffer *buffer,
1446                                        GtkTextIter   *location,
1447                                        gchar         *text,
1448                                        gint           len,
1449                                        EmpathyChat   *chat)
1450 {
1451         GtkTextIter iter, pos;
1452
1453         /* Remove all misspelled tags in the inserted text.
1454          * This happens when text is inserted within a misspelled word. */
1455         gtk_text_buffer_get_iter_at_offset (buffer, &iter,
1456                                             gtk_text_iter_get_offset (location) - len);
1457         gtk_text_buffer_remove_tag_by_name (buffer, "misspelled",
1458                                             &iter, location);
1459
1460         gtk_text_buffer_get_iter_at_mark (buffer, &pos, gtk_text_buffer_get_insert (buffer));
1461
1462         do {
1463                 GtkTextIter start, end;
1464                 gchar *str;
1465
1466                 if (!chat_input_text_get_word_from_iter (&iter, &start, &end))
1467                         continue;
1468
1469                 str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1470
1471                 if (gtk_text_iter_in_range (&pos, &start, &end) ||
1472                                 gtk_text_iter_equal (&pos, &end) ||
1473                                 empathy_spell_check (str)) {
1474                         gtk_text_buffer_remove_tag_by_name (buffer, "misspelled", &start, &end);
1475                 } else {
1476                         gtk_text_buffer_apply_tag_by_name (buffer, "misspelled", &start, &end);
1477                 }
1478
1479                 g_free (str);
1480
1481         } while (gtk_text_iter_forward_word_end (&iter) &&
1482                  gtk_text_iter_compare (&iter, location) <= 0);
1483 }
1484
1485 static void
1486 chat_input_text_buffer_delete_range_cb (GtkTextBuffer *buffer,
1487                                         GtkTextIter   *start,
1488                                         GtkTextIter   *end,
1489                                         EmpathyChat   *chat)
1490 {
1491         GtkTextIter word_start, word_end;
1492
1493         if (chat_input_text_get_word_from_iter (start, &word_start, &word_end)) {
1494                 gtk_text_buffer_remove_tag_by_name (buffer, "misspelled",
1495                                                     &word_start, &word_end);
1496         }
1497 }
1498
1499 static void
1500 chat_input_text_buffer_changed_cb (GtkTextBuffer *buffer,
1501                                    EmpathyChat    *chat)
1502 {
1503         if (gtk_text_buffer_get_char_count (buffer) == 0) {
1504                 chat_composing_stop (chat);
1505         } else {
1506                 chat_composing_start (chat);
1507         }
1508 }
1509
1510 static void
1511 chat_input_text_buffer_notify_cursor_position_cb (GtkTextBuffer *buffer,
1512                                                   GParamSpec    *pspec,
1513                                                   EmpathyChat    *chat)
1514 {
1515         GtkTextIter pos;
1516         GtkTextIter prev_pos;
1517         GtkTextIter word_start;
1518         GtkTextIter word_end;
1519         GtkTextMark *mark;
1520         gchar *str;
1521
1522         mark = gtk_text_buffer_get_mark (buffer, "previous-cursor-position");
1523
1524         gtk_text_buffer_get_iter_at_mark (buffer, &pos,
1525                                           gtk_text_buffer_get_insert (buffer));
1526         gtk_text_buffer_get_iter_at_mark (buffer, &prev_pos, mark);
1527
1528         if (!chat_input_text_get_word_from_iter (&prev_pos, &word_start, &word_end))
1529                 goto out;
1530
1531         if (!gtk_text_iter_in_range (&pos, &word_start, &word_end) &&
1532                         !gtk_text_iter_equal (&pos, &word_end)) {
1533                 str = gtk_text_buffer_get_text (buffer,
1534                                         &word_start, &word_end, FALSE);
1535
1536                 if (!empathy_spell_check (str)) {
1537                         gtk_text_buffer_apply_tag_by_name (buffer,
1538                                         "misspelled", &word_start, &word_end);
1539                 } else {
1540                         gtk_text_buffer_remove_tag_by_name (buffer,
1541                                         "misspelled", &word_start, &word_end);
1542                 }
1543
1544                 g_free (str);
1545         }
1546
1547 out:
1548         gtk_text_buffer_move_mark (buffer, mark, &pos);
1549 }
1550
1551 static gboolean
1552 empathy_isspace_cb (gunichar c,
1553                  gpointer data)
1554 {
1555         return g_unichar_isspace (c);
1556 }
1557
1558 static gboolean
1559 chat_input_key_press_event_cb (GtkWidget   *widget,
1560                                GdkEventKey *event,
1561                                EmpathyChat *chat)
1562 {
1563         EmpathyChatPriv *priv;
1564         GtkAdjustment  *adj;
1565         gdouble         val;
1566         GtkWidget      *text_view_sw;
1567
1568         priv = GET_PRIV (chat);
1569
1570         /* Catch ctrl+up/down so we can traverse messages we sent */
1571         if ((event->state & GDK_CONTROL_MASK) &&
1572             (event->keyval == GDK_KEY_Up ||
1573              event->keyval == GDK_KEY_Down)) {
1574                 GtkTextBuffer *buffer;
1575                 const gchar   *str;
1576
1577                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1578                 chat_input_history_update (chat, buffer);
1579
1580                 if (event->keyval == GDK_KEY_Up) {
1581                         str = chat_input_history_get_next (chat);
1582                 } else {
1583                         str = chat_input_history_get_prev (chat);
1584                 }
1585
1586                 g_signal_handlers_block_by_func (buffer,
1587                                                  chat_input_text_buffer_changed_cb,
1588                                                  chat);
1589                 gtk_text_buffer_set_text (buffer, str ? str : "", -1);
1590                 g_signal_handlers_unblock_by_func (buffer,
1591                                                    chat_input_text_buffer_changed_cb,
1592                                                    chat);
1593
1594                 return TRUE;
1595         }
1596
1597         /* Catch enter but not ctrl/shift-enter */
1598         if (IS_ENTER (event->keyval) &&
1599             !(event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
1600                 GtkTextView *view;
1601
1602                 /* This is to make sure that kinput2 gets the enter. And if
1603                  * it's handled there we shouldn't send on it. This is because
1604                  * kinput2 uses Enter to commit letters. See:
1605                  * http://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=104299
1606                  */
1607
1608                 view = GTK_TEXT_VIEW (chat->input_text_view);
1609                 if (gtk_text_view_im_context_filter_keypress (view, event)) {
1610                         gtk_text_view_reset_im_context (view);
1611                         return TRUE;
1612                 }
1613
1614                 chat_input_text_view_send (chat);
1615                 return TRUE;
1616         }
1617
1618         text_view_sw = gtk_widget_get_parent (GTK_WIDGET (chat->view));
1619
1620         if (IS_ENTER (event->keyval) &&
1621             (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
1622                 /* Newline for shift/control-enter. */
1623                 return FALSE;
1624         }
1625         if (!(event->state & GDK_CONTROL_MASK) &&
1626             event->keyval == GDK_KEY_Page_Up) {
1627                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
1628                 gtk_adjustment_set_value (adj, gtk_adjustment_get_value (adj) - gtk_adjustment_get_page_size (adj));
1629                 return TRUE;
1630         }
1631         if ((event->state & GDK_CONTROL_MASK) != GDK_CONTROL_MASK &&
1632             event->keyval == GDK_KEY_Page_Down) {
1633                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
1634                 val = MIN (gtk_adjustment_get_value (adj) + gtk_adjustment_get_page_size (adj),
1635                            gtk_adjustment_get_upper (adj) - gtk_adjustment_get_page_size (adj));
1636                 gtk_adjustment_set_value (adj, val);
1637                 return TRUE;
1638         }
1639         if (event->keyval == GDK_KEY_Escape) {
1640                 empathy_search_bar_hide (EMPATHY_SEARCH_BAR (priv->search_bar));
1641         }
1642         if (!(event->state & (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) &&
1643             event->keyval == GDK_KEY_Tab) {
1644                 GtkTextBuffer *buffer;
1645                 GtkTextIter    start, current;
1646                 gchar         *nick, *completed;
1647                 GList         *list, *completed_list;
1648                 gboolean       is_start_of_buffer;
1649
1650                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (EMPATHY_CHAT (chat)->input_text_view));
1651                 gtk_text_buffer_get_iter_at_mark (buffer, &current, gtk_text_buffer_get_insert (buffer));
1652
1653                 /* Get the start of the nick to complete. */
1654                 gtk_text_buffer_get_iter_at_mark (buffer, &start, gtk_text_buffer_get_insert (buffer));
1655                 if (gtk_text_iter_backward_find_char (&start, &empathy_isspace_cb, NULL, NULL)) {
1656                         gtk_text_iter_set_offset (&start, gtk_text_iter_get_offset (&start) + 1);
1657                 }
1658                 is_start_of_buffer = gtk_text_iter_is_start (&start);
1659
1660                 list = empathy_contact_list_get_members (EMPATHY_CONTACT_LIST (priv->tp_chat));
1661                 g_completion_add_items (priv->completion, list);
1662
1663                 nick = gtk_text_buffer_get_text (buffer, &start, &current, FALSE);
1664                 completed_list = g_completion_complete (priv->completion,
1665                                                         nick,
1666                                                         &completed);
1667
1668                 g_free (nick);
1669
1670                 if (completed) {
1671                         guint        len;
1672                         const gchar *text;
1673                         GString     *message = NULL;
1674                         GList       *l;
1675
1676                         gtk_text_buffer_delete (buffer, &start, &current);
1677
1678                         len = g_list_length (completed_list);
1679
1680                         if (len == 1) {
1681                                 /* If we only have one hit, use that text
1682                                  * instead of the text in completed since the
1683                                  * completed text will use the typed string
1684                                  * which might be cased all wrong.
1685                                  * Fixes #120876
1686                                  * */
1687                                 text = empathy_contact_get_alias (completed_list->data);
1688                         } else {
1689                                 text = completed;
1690
1691                                 /* Print all hits to the scrollback view, so the
1692                                  * user knows what possibilities he has.
1693                                  * Fixes #599779
1694                                  * */
1695                                  message = g_string_new ("");
1696                                  for (l = completed_list; l != NULL; l = l->next) {
1697                                         g_string_append (message, empathy_contact_get_alias (l->data));
1698                                         g_string_append (message, " - ");
1699                                  }
1700                                  empathy_chat_view_append_event (chat->view, message->str);
1701                                  g_string_free (message, TRUE);
1702                         }
1703
1704                         gtk_text_buffer_insert_at_cursor (buffer, text, strlen (text));
1705
1706                         if (len == 1 && is_start_of_buffer) {
1707                             gchar *complete_char;
1708
1709                             complete_char = g_settings_get_string (
1710                                     priv->gsettings_chat,
1711                                     EMPATHY_PREFS_CHAT_NICK_COMPLETION_CHAR);
1712
1713                             if (complete_char != NULL) {
1714                                 gtk_text_buffer_insert_at_cursor (buffer,
1715                                                                   complete_char,
1716                                                                   strlen (complete_char));
1717                                 gtk_text_buffer_insert_at_cursor (buffer, " ", 1);
1718                                 g_free (complete_char);
1719                             }
1720                         }
1721
1722                         g_free (completed);
1723                 }
1724
1725                 g_completion_clear_items (priv->completion);
1726
1727                 g_list_foreach (list, (GFunc) g_object_unref, NULL);
1728                 g_list_free (list);
1729
1730                 return TRUE;
1731         }
1732
1733         return FALSE;
1734 }
1735
1736 static gboolean
1737 chat_text_view_focus_in_event_cb (GtkWidget  *widget,
1738                                   GdkEvent   *event,
1739                                   EmpathyChat *chat)
1740 {
1741         gtk_widget_grab_focus (chat->input_text_view);
1742
1743         return TRUE;
1744 }
1745
1746 static void
1747 chat_input_realize_cb (GtkWidget   *widget,
1748                        EmpathyChat *chat)
1749 {
1750         DEBUG ("Setting focus to the input text view");
1751         if (gtk_widget_is_sensitive (widget)) {
1752                 gtk_widget_grab_focus (widget);
1753         }
1754 }
1755
1756 static void
1757 chat_input_has_focus_notify_cb (GtkWidget   *widget,
1758                                 GParamSpec  *pspec,
1759                                 EmpathyChat *chat)
1760 {
1761         empathy_chat_view_focus_toggled (chat->view, gtk_widget_has_focus (widget));
1762 }
1763
1764 static void
1765 chat_insert_smiley_activate_cb (EmpathySmileyManager *manager,
1766                                 EmpathySmiley        *smiley,
1767                                 gpointer              user_data)
1768 {
1769         EmpathyChat   *chat = EMPATHY_CHAT (user_data);
1770         GtkTextBuffer *buffer;
1771         GtkTextIter    iter;
1772
1773         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1774
1775         gtk_text_buffer_get_end_iter (buffer, &iter);
1776         gtk_text_buffer_insert (buffer, &iter, smiley->str, -1);
1777
1778         gtk_text_buffer_get_end_iter (buffer, &iter);
1779         gtk_text_buffer_insert (buffer, &iter, " ", -1);
1780 }
1781
1782 typedef struct {
1783         EmpathyChat  *chat;
1784         gchar       *word;
1785
1786         GtkTextIter  start;
1787         GtkTextIter  end;
1788 } EmpathyChatSpell;
1789
1790 static EmpathyChatSpell *
1791 chat_spell_new (EmpathyChat  *chat,
1792                 const gchar *word,
1793                 GtkTextIter  start,
1794                 GtkTextIter  end)
1795 {
1796         EmpathyChatSpell *chat_spell;
1797
1798         chat_spell = g_slice_new0 (EmpathyChatSpell);
1799
1800         chat_spell->chat = g_object_ref (chat);
1801         chat_spell->word = g_strdup (word);
1802         chat_spell->start = start;
1803         chat_spell->end = end;
1804
1805         return chat_spell;
1806 }
1807
1808 static void
1809 chat_spell_free (EmpathyChatSpell *chat_spell)
1810 {
1811         g_object_unref (chat_spell->chat);
1812         g_free (chat_spell->word);
1813         g_slice_free (EmpathyChatSpell, chat_spell);
1814 }
1815
1816 static void
1817 chat_spelling_menu_activate_cb (GtkMenuItem     *menu_item,
1818                                                 EmpathyChatSpell *chat_spell)
1819 {
1820     empathy_chat_correct_word (chat_spell->chat,
1821                                &(chat_spell->start),
1822                                &(chat_spell->end),
1823                                gtk_menu_item_get_label (menu_item));
1824 }
1825
1826
1827 static GtkWidget *
1828 chat_spelling_build_suggestions_menu (const gchar *code,
1829                                       EmpathyChatSpell *chat_spell)
1830 {
1831         GList     *suggestions, *l;
1832         GtkWidget *menu, *menu_item;
1833
1834         suggestions = empathy_spell_get_suggestions (code, chat_spell->word);
1835         if (suggestions == NULL)
1836                 return NULL;
1837
1838         menu = gtk_menu_new ();
1839         for (l = suggestions; l; l = l->next) {
1840                 menu_item = gtk_menu_item_new_with_label (l->data);
1841                 g_signal_connect (G_OBJECT (menu_item), "activate",
1842                                   G_CALLBACK (chat_spelling_menu_activate_cb),
1843                                   chat_spell);
1844                 gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
1845         }
1846         empathy_spell_free_suggestions (suggestions);
1847
1848         gtk_widget_show_all (menu);
1849
1850         return menu;
1851 }
1852
1853 static GtkWidget *
1854 chat_spelling_build_menu (EmpathyChatSpell *chat_spell)
1855 {
1856         GtkWidget *menu, *submenu, *item;
1857         GList     *codes, *l;
1858
1859         codes = empathy_spell_get_enabled_language_codes ();
1860         g_assert (codes != NULL);
1861
1862         if (g_list_length (codes) > 1) {
1863                 menu = gtk_menu_new ();
1864
1865                 for (l = codes; l; l = l->next) {
1866                         const gchar *code, *name;
1867
1868                         code = l->data;
1869                         name = empathy_spell_get_language_name (code);
1870                         if (!name)
1871                                 continue;
1872
1873                         item = gtk_image_menu_item_new_with_label (name);
1874
1875                         submenu = chat_spelling_build_suggestions_menu (
1876                                         code, chat_spell);
1877                         if (submenu == NULL)
1878                                 gtk_widget_set_sensitive (item, FALSE);
1879                         else
1880                                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item),
1881                                                            submenu);
1882                         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1883                 }
1884         } else {
1885                 menu = chat_spelling_build_suggestions_menu (codes->data,
1886                                                              chat_spell);
1887                 if (menu == NULL) {
1888                         menu = gtk_menu_new ();
1889                         item = gtk_menu_item_new_with_label (_("(No Suggestions)"));
1890                         gtk_widget_set_sensitive (item, FALSE);
1891                         gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
1892                 }
1893         }
1894         g_list_free (codes);
1895
1896         gtk_widget_show_all (menu);
1897
1898         return menu;
1899 }
1900
1901 typedef struct {
1902         EmpathyChat  *chat;
1903         gchar        *word;
1904         gchar        *code;
1905 } EmpathyChatWord;
1906
1907 static EmpathyChatWord *
1908 chat_word_new (EmpathyChat  *chat,
1909                 const gchar  *word,
1910                 const gchar  *code)
1911 {
1912         EmpathyChatWord *chat_word;
1913
1914         chat_word = g_slice_new0 (EmpathyChatWord);
1915
1916         chat_word->chat = g_object_ref (chat);
1917         chat_word->word = g_strdup (word);
1918         chat_word->code = g_strdup (code);
1919
1920         return chat_word;
1921 }
1922
1923 static void
1924 chat_word_free (EmpathyChatWord *chat_word)
1925 {
1926         g_object_unref (chat_word->chat);
1927         g_free (chat_word->word);
1928         g_free (chat_word->code);
1929         g_slice_free (EmpathyChatWord, chat_word);
1930 }
1931
1932 static void
1933 chat_add_to_dictionary_activate_cb (GtkMenuItem     *menu_item,
1934                                     EmpathyChatWord *chat_word)
1935 {
1936         EmpathyChatPriv *priv = GET_PRIV (chat_word->chat);
1937
1938         empathy_spell_add_to_dictionary (chat_word->code,
1939                                          chat_word->word);
1940         priv->update_misspelled_words_id =
1941                 g_idle_add (update_misspelled_words, chat_word->chat);
1942 }
1943
1944 static GtkWidget *
1945 chat_spelling_build_add_to_dictionary_item (EmpathyChatSpell *chat_spell)
1946 {
1947         GtkWidget       *menu, *item, *lang_item, *image;
1948         GList           *codes, *l;
1949         gchar           *label;
1950         const gchar     *code, *name;
1951         EmpathyChatWord *chat_word;
1952
1953         codes = empathy_spell_get_enabled_language_codes ();
1954         g_assert (codes != NULL);
1955         if (g_list_length (codes) > 1) {
1956                 /* translators: %s is the selected word */
1957                 label = g_strdup_printf (_("Add '%s' to Dictionary"),
1958                                         chat_spell->word);
1959                 item = gtk_image_menu_item_new_with_mnemonic (label);
1960                 g_free (label);
1961                 image = gtk_image_new_from_icon_name (GTK_STOCK_ADD,
1962                                                       GTK_ICON_SIZE_MENU);
1963                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item),
1964                                                image);
1965
1966                 menu = gtk_menu_new ();
1967
1968                 for (l = codes; l; l = l->next) {
1969                         code = l->data;
1970                         name = empathy_spell_get_language_name (code);
1971                         if (name == NULL)
1972                                 continue;
1973
1974                         lang_item = gtk_image_menu_item_new_with_label (name);
1975
1976                         chat_word= chat_word_new (chat_spell->chat,
1977                                                   chat_spell->word, code);
1978                         g_object_set_data_full (G_OBJECT (lang_item),
1979                                 "chat-word", chat_word,
1980                                 (GDestroyNotify) chat_word_free);
1981
1982                         g_signal_connect (G_OBJECT (lang_item), "activate",
1983                                 G_CALLBACK (chat_add_to_dictionary_activate_cb),
1984                                 chat_word);
1985                         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), lang_item);
1986                 }
1987                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), menu);
1988         } else {
1989                 code = codes->data;
1990                 name = empathy_spell_get_language_name (code);
1991                 g_assert (name != NULL);
1992                 /* translators: first %s is the selected word,
1993                  * second %s is the language name of the target dictionary */
1994                 label = g_strdup_printf (_("Add '%s' to %s Dictionary"),
1995                                         chat_spell->word, name);
1996                 item = gtk_image_menu_item_new_with_mnemonic (label);
1997                 g_free (label);
1998                 image = gtk_image_new_from_icon_name (GTK_STOCK_ADD,
1999                                                       GTK_ICON_SIZE_MENU);
2000                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
2001
2002                 chat_word = chat_word_new (chat_spell->chat, chat_spell->word,
2003                                            code);
2004                 g_object_set_data_full (G_OBJECT (item), "chat-word", chat_word,
2005                                         (GDestroyNotify) chat_word_free);
2006
2007                 g_signal_connect (G_OBJECT (item), "activate",
2008                                   G_CALLBACK (chat_add_to_dictionary_activate_cb),
2009                                   chat_word);
2010         }
2011         g_list_free (codes);
2012
2013         gtk_widget_show_all (item);
2014
2015         return item;
2016 }
2017
2018 static void
2019 chat_text_send_cb (GtkMenuItem *menuitem,
2020                    EmpathyChat *chat)
2021 {
2022         chat_input_text_view_send (chat);
2023 }
2024
2025 static void
2026 chat_input_populate_popup_cb (GtkTextView *view,
2027                               GtkMenu     *menu,
2028                               EmpathyChat *chat)
2029 {
2030         GtkTextBuffer        *buffer;
2031         GtkTextTagTable      *table;
2032         GtkTextTag           *tag;
2033         gint                  x, y;
2034         GtkTextIter           iter, start, end;
2035         GtkWidget            *item;
2036         gchar                *str = NULL;
2037         EmpathyChatSpell     *chat_spell;
2038         GtkWidget            *spell_menu;
2039         GtkWidget            *spell_item;
2040         EmpathySmileyManager *smiley_manager;
2041         GtkWidget            *smiley_menu;
2042         GtkWidget            *image;
2043
2044         buffer = gtk_text_view_get_buffer (view);
2045
2046         /* Add the emoticon menu. */
2047         item = gtk_separator_menu_item_new ();
2048         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2049         gtk_widget_show (item);
2050
2051         item = gtk_image_menu_item_new_with_mnemonic (_("Insert Smiley"));
2052         image = gtk_image_new_from_icon_name ("face-smile",
2053                                               GTK_ICON_SIZE_MENU);
2054         gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
2055         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2056         gtk_widget_show (item);
2057
2058         smiley_manager = empathy_smiley_manager_dup_singleton ();
2059         smiley_menu = empathy_smiley_menu_new (smiley_manager,
2060                                                chat_insert_smiley_activate_cb,
2061                                                chat);
2062         gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), smiley_menu);
2063         g_object_unref (smiley_manager);
2064
2065         /* Add the Send menu item. */
2066         gtk_text_buffer_get_bounds (buffer, &start, &end);
2067         str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
2068         if (!EMP_STR_EMPTY (str)) {
2069                 item = gtk_menu_item_new_with_mnemonic (_("_Send"));
2070                 g_signal_connect (G_OBJECT (item), "activate",
2071                                   G_CALLBACK (chat_text_send_cb), chat);
2072                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2073                 gtk_widget_show (item);
2074         }
2075         str = NULL;
2076
2077         /* Add the spell check menu item. */
2078         table = gtk_text_buffer_get_tag_table (buffer);
2079         tag = gtk_text_tag_table_lookup (table, "misspelled");
2080         gtk_widget_get_pointer (GTK_WIDGET (view), &x, &y);
2081         gtk_text_view_window_to_buffer_coords (GTK_TEXT_VIEW (view),
2082                                                GTK_TEXT_WINDOW_WIDGET,
2083                                                x, y,
2084                                                &x, &y);
2085         gtk_text_view_get_iter_at_location (GTK_TEXT_VIEW (view), &iter, x, y);
2086         start = end = iter;
2087         if (gtk_text_iter_backward_to_tag_toggle (&start, tag) &&
2088             gtk_text_iter_forward_to_tag_toggle (&end, tag)) {
2089
2090                 str = gtk_text_buffer_get_text (buffer,
2091                                                 &start, &end, FALSE);
2092         }
2093         if (!EMP_STR_EMPTY (str)) {
2094                 chat_spell = chat_spell_new (chat, str, start, end);
2095                 g_object_set_data_full (G_OBJECT (menu),
2096                                         "chat-spell", chat_spell,
2097                                         (GDestroyNotify) chat_spell_free);
2098
2099                 item = gtk_separator_menu_item_new ();
2100                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2101                 gtk_widget_show (item);
2102
2103                 /* Spelling suggestions */
2104                 item = gtk_image_menu_item_new_with_mnemonic (_("_Spelling Suggestions"));
2105                 image = gtk_image_new_from_icon_name (GTK_STOCK_SPELL_CHECK,
2106                                                       GTK_ICON_SIZE_MENU);
2107                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
2108
2109                 spell_menu = chat_spelling_build_menu (chat_spell);
2110                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), spell_menu);
2111
2112
2113                 spell_item = gtk_separator_menu_item_new ();
2114                 gtk_menu_shell_append (GTK_MENU_SHELL (spell_menu), spell_item);
2115                 gtk_widget_show (spell_item);
2116
2117                 /* Add to dictionary */
2118                 spell_item = chat_spelling_build_add_to_dictionary_item (chat_spell);
2119
2120                 gtk_menu_shell_append (GTK_MENU_SHELL (spell_menu), spell_item);
2121                 gtk_widget_show (spell_item);
2122
2123                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2124                 gtk_widget_show (item);
2125         }
2126 }
2127
2128
2129 static gboolean
2130 chat_log_filter (TplEvent *log,
2131                  gpointer user_data)
2132 {
2133         EmpathyChat *chat = user_data;
2134         EmpathyMessage *message;
2135         EmpathyChatPriv *priv = GET_PRIV (chat);
2136         const GList *pending;
2137
2138         g_return_val_if_fail (TPL_IS_EVENT (log), FALSE);
2139         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
2140
2141         pending = empathy_tp_chat_get_pending_messages (priv->tp_chat);
2142         message = empathy_message_from_tpl_log_event (log);
2143
2144         for (; pending; pending = g_list_next (pending)) {
2145                 if (empathy_message_equal (message, pending->data)) {
2146                         g_object_unref (message);
2147                         return FALSE;
2148                 }
2149         }
2150
2151         g_object_unref (message);
2152         return TRUE;
2153 }
2154
2155
2156 static void
2157 show_pending_messages (EmpathyChat *chat) {
2158         EmpathyChatPriv *priv = GET_PRIV (chat);
2159         const GList *messages, *l;
2160
2161         g_return_if_fail (EMPATHY_IS_CHAT (chat));
2162
2163         if (chat->view == NULL || priv->tp_chat == NULL)
2164                 return;
2165
2166         if (!priv->can_show_pending)
2167                 return;
2168
2169         messages = empathy_tp_chat_get_pending_messages (priv->tp_chat);
2170
2171         for (l = messages; l != NULL ; l = g_list_next (l)) {
2172                 EmpathyMessage *message = EMPATHY_MESSAGE (l->data);
2173                 chat_message_received (chat, message, TRUE);
2174         }
2175 }
2176
2177
2178 static void
2179 got_filtered_messages_cb (GObject *manager,
2180                 GAsyncResult *result,
2181                 gpointer user_data)
2182 {
2183         GList *l;
2184         GList *messages;
2185         EmpathyChat *chat = EMPATHY_CHAT (user_data);
2186         EmpathyChatPriv *priv = GET_PRIV (chat);
2187         GError *error = NULL;
2188
2189         if (!tpl_log_manager_get_filtered_events_finish (TPL_LOG_MANAGER (manager),
2190                 result, &messages, &error)) {
2191                 DEBUG ("%s. Aborting.", error->message);
2192                 empathy_chat_view_append_event (chat->view,
2193                         _("Failed to retrieve recent logs"));
2194                 g_error_free (error);
2195                 goto out;
2196         }
2197
2198         for (l = messages; l; l = g_list_next (l)) {
2199                 EmpathyMessage *message;
2200                 g_assert (TPL_IS_EVENT (l->data));
2201
2202                 message = empathy_message_from_tpl_log_event (l->data);
2203                 g_object_unref (l->data);
2204
2205                 empathy_chat_view_append_message (chat->view, message);
2206                 g_object_unref (message);
2207         }
2208         g_list_free (messages);
2209
2210 out:
2211         /* in case of TPL error, skip backlog and show pending messages */
2212         priv->can_show_pending = TRUE;
2213         show_pending_messages (chat);
2214
2215         /* FIXME: See Bug#610994, we are forcing the ACK of the queue. See comments
2216          * about it in EmpathyChatPriv definition */
2217         priv->retrieving_backlogs = FALSE;
2218         empathy_chat_messages_read (chat);
2219
2220         /* Turn back on scrolling */
2221         empathy_chat_view_scroll (chat->view, TRUE);
2222 }
2223
2224 static void
2225 chat_add_logs (EmpathyChat *chat)
2226 {
2227         EmpathyChatPriv *priv = GET_PRIV (chat);
2228         TplEntity       *target;
2229
2230         if (!priv->id) {
2231                 return;
2232         }
2233
2234         /* Turn off scrolling temporarily */
2235         empathy_chat_view_scroll (chat->view, FALSE);
2236
2237         /* Add messages from last conversation */
2238         if (priv->handle_type == TP_HANDLE_TYPE_ROOM)
2239           target = tpl_entity_new_from_room_id (priv->id);
2240         else
2241           target = tpl_entity_new (priv->id, TPL_ENTITY_CONTACT, NULL, NULL);
2242
2243         priv->retrieving_backlogs = TRUE;
2244         tpl_log_manager_get_filtered_events_async (priv->log_manager,
2245                                                    priv->account,
2246                                                    target,
2247                                                    TPL_EVENT_MASK_TEXT,
2248                                                    5,
2249                                                    chat_log_filter,
2250                                                    chat,
2251                                                    got_filtered_messages_cb,
2252                                                    (gpointer) chat);
2253
2254         g_object_unref (target);
2255 }
2256
2257 static gint
2258 chat_contacts_completion_func (const gchar *s1,
2259                                const gchar *s2,
2260                                gsize        n)
2261 {
2262         gchar *tmp, *nick1, *nick2;
2263         gint   ret;
2264
2265         if (s1 == s2) {
2266                 return 0;
2267         }
2268         if (!s1 || !s2) {
2269                 return s1 ? -1 : +1;
2270         }
2271
2272         tmp = g_utf8_normalize (s1, -1, G_NORMALIZE_DEFAULT);
2273         nick1 = g_utf8_casefold (tmp, -1);
2274         g_free (tmp);
2275
2276         tmp = g_utf8_normalize (s2, -1, G_NORMALIZE_DEFAULT);
2277         nick2 = g_utf8_casefold (tmp, -1);
2278         g_free (tmp);
2279
2280         ret = strncmp (nick1, nick2, n);
2281
2282         g_free (nick1);
2283         g_free (nick2);
2284
2285         return ret;
2286 }
2287
2288 static gchar *
2289 build_part_message (guint           reason,
2290                     const gchar    *name,
2291                     EmpathyContact *actor,
2292                     const gchar    *message)
2293 {
2294         GString *s = g_string_new ("");
2295         const gchar *actor_name = NULL;
2296
2297         if (actor != NULL) {
2298                 actor_name = empathy_contact_get_alias (actor);
2299         }
2300
2301         /* Having an actor only really makes sense for a few actions... */
2302         switch (reason) {
2303         case TP_CHANNEL_GROUP_CHANGE_REASON_OFFLINE:
2304                 g_string_append_printf (s, _("%s has disconnected"), name);
2305                 break;
2306         case TP_CHANNEL_GROUP_CHANGE_REASON_KICKED:
2307                 if (actor_name != NULL) {
2308                         /* translators: reverse the order of these arguments
2309                          * if the kicked should come before the kicker in your locale.
2310                          */
2311                         g_string_append_printf (s, _("%1$s was kicked by %2$s"),
2312                                 name, actor_name);
2313                 } else {
2314                         g_string_append_printf (s, _("%s was kicked"), name);
2315                 }
2316                 break;
2317         case TP_CHANNEL_GROUP_CHANGE_REASON_BANNED:
2318                 if (actor_name != NULL) {
2319                         /* translators: reverse the order of these arguments
2320                          * if the banned should come before the banner in your locale.
2321                          */
2322                         g_string_append_printf (s, _("%1$s was banned by %2$s"),
2323                                 name, actor_name);
2324                 } else {
2325                         g_string_append_printf (s, _("%s was banned"), name);
2326                 }
2327                 break;
2328         default:
2329                 g_string_append_printf (s, _("%s has left the room"), name);
2330         }
2331
2332         if (!EMP_STR_EMPTY (message)) {
2333                 /* Note to translators: this string is appended to
2334                  * notifications like "foo has left the room", with the message
2335                  * given by the user living the room. If this poses a problem,
2336                  * please let us know. :-)
2337                  */
2338                 g_string_append_printf (s, _(" (%s)"), message);
2339         }
2340
2341         return g_string_free (s, FALSE);
2342 }
2343
2344 static void
2345 chat_members_changed_cb (EmpathyTpChat  *tp_chat,
2346                          EmpathyContact *contact,
2347                          EmpathyContact *actor,
2348                          guint           reason,
2349                          gchar          *message,
2350                          gboolean        is_member,
2351                          EmpathyChat    *chat)
2352 {
2353         EmpathyChatPriv *priv = GET_PRIV (chat);
2354         const gchar *name = empathy_contact_get_alias (contact);
2355         gchar *str;
2356
2357         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED != reason);
2358
2359         if (priv->block_events_timeout_id != 0)
2360                 return;
2361
2362         if (is_member) {
2363                 str = g_strdup_printf (_("%s has joined the room"),
2364                                        name);
2365         } else {
2366                 str = build_part_message (reason, name, actor, message);
2367         }
2368
2369         empathy_chat_view_append_event (chat->view, str);
2370         g_free (str);
2371 }
2372
2373 static void
2374 chat_member_renamed_cb (EmpathyTpChat  *tp_chat,
2375                          EmpathyContact *old_contact,
2376                          EmpathyContact *new_contact,
2377                          guint           reason,
2378                          gchar          *message,
2379                          EmpathyChat    *chat)
2380 {
2381         EmpathyChatPriv *priv = GET_PRIV (chat);
2382
2383         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED == reason);
2384
2385         if (priv->block_events_timeout_id == 0) {
2386                 gchar *str;
2387
2388                 str = g_strdup_printf (_("%s is now known as %s"),
2389                                        empathy_contact_get_alias (old_contact),
2390                                        empathy_contact_get_alias (new_contact));
2391                 empathy_chat_view_append_event (chat->view, str);
2392                 g_free (str);
2393         }
2394
2395 }
2396
2397 static gboolean
2398 chat_reset_size_request (gpointer widget)
2399 {
2400         gtk_widget_set_size_request (widget, -1, -1);
2401
2402         return FALSE;
2403 }
2404
2405 static void
2406 chat_update_contacts_visibility (EmpathyChat *chat,
2407                          gboolean show)
2408 {
2409         EmpathyChatPriv *priv = GET_PRIV (chat);
2410         GtkAllocation allocation;
2411
2412         if (!priv->scrolled_window_contacts) {
2413                 return;
2414         }
2415
2416         if (priv->remote_contact != NULL) {
2417                 show = FALSE;
2418         }
2419
2420         if (show && priv->contact_list_view == NULL) {
2421                 EmpathyContactListStore *store;
2422                 gint                     min_width;
2423
2424                 /* We are adding the contact list to the chat, we don't want the
2425                  * chat view to become too small. If the chat view is already
2426                  * smaller than 250 make sure that size won't change. If the
2427                  * chat view is bigger the contact list will take some space on
2428                  * it but we make sure the chat view don't become smaller than
2429                  * 250. Relax the size request once the resize is done */
2430                 gtk_widget_get_allocation (priv->vbox_left, &allocation);
2431                 min_width = MIN (allocation.width, 250);
2432                 gtk_widget_set_size_request (priv->vbox_left, min_width, -1);
2433                 g_idle_add (chat_reset_size_request, priv->vbox_left);
2434
2435                 if (priv->contacts_width > 0) {
2436                         gtk_paned_set_position (GTK_PANED (priv->hpaned),
2437                                                 priv->contacts_width);
2438                 }
2439
2440                 store = empathy_contact_list_store_new (
2441                                 EMPATHY_CONTACT_LIST (priv->tp_chat));
2442                 empathy_contact_list_store_set_show_groups (
2443                                 EMPATHY_CONTACT_LIST_STORE (store), FALSE);
2444
2445                 priv->contact_list_view = GTK_WIDGET (empathy_contact_list_view_new (store,
2446                         EMPATHY_CONTACT_LIST_FEATURE_CONTACT_TOOLTIP,
2447                         EMPATHY_CONTACT_FEATURE_CHAT |
2448                         EMPATHY_CONTACT_FEATURE_CALL |
2449                         EMPATHY_CONTACT_FEATURE_LOG |
2450                         EMPATHY_CONTACT_FEATURE_INFO));
2451                 gtk_container_add (GTK_CONTAINER (priv->scrolled_window_contacts),
2452                                    priv->contact_list_view);
2453                 gtk_widget_show (priv->contact_list_view);
2454                 gtk_widget_show (priv->scrolled_window_contacts);
2455                 g_object_unref (store);
2456         } else if (!show) {
2457                 priv->contacts_width = gtk_paned_get_position (GTK_PANED (priv->hpaned));
2458                 gtk_widget_hide (priv->scrolled_window_contacts);
2459                 if (priv->contact_list_view != NULL) {
2460                         gtk_widget_destroy (priv->contact_list_view);
2461                         priv->contact_list_view = NULL;
2462                 }
2463         }
2464 }
2465
2466 void
2467 empathy_chat_set_show_contacts (EmpathyChat *chat,
2468                                 gboolean     show)
2469 {
2470         EmpathyChatPriv *priv = GET_PRIV (chat);
2471
2472         priv->show_contacts = show;
2473
2474         chat_update_contacts_visibility (chat, show);
2475
2476         g_object_notify (G_OBJECT (chat), "show-contacts");
2477 }
2478
2479 static void
2480 chat_remote_contact_changed_cb (EmpathyChat *chat)
2481 {
2482         EmpathyChatPriv *priv = GET_PRIV (chat);
2483
2484         if (priv->remote_contact != NULL) {
2485                 g_object_unref (priv->remote_contact);
2486                 priv->remote_contact = NULL;
2487         }
2488
2489         g_free (priv->id);
2490
2491         priv->id = g_strdup (empathy_tp_chat_get_id (priv->tp_chat));
2492         priv->remote_contact = empathy_tp_chat_get_remote_contact (priv->tp_chat);
2493         if (priv->remote_contact != NULL) {
2494                 g_object_ref (priv->remote_contact);
2495                 priv->handle_type = TP_HANDLE_TYPE_CONTACT;
2496         }
2497         else if (priv->tp_chat != NULL) {
2498                 TpChannel *channel;
2499
2500                 channel = empathy_tp_chat_get_channel (priv->tp_chat);
2501                 g_object_get (channel, "handle-type", &priv->handle_type, NULL);
2502         }
2503
2504         chat_update_contacts_visibility (chat, priv->show_contacts);
2505
2506         g_object_notify (G_OBJECT (chat), "remote-contact");
2507         g_object_notify (G_OBJECT (chat), "id");
2508 }
2509
2510 static void
2511 chat_destroy_cb (EmpathyTpChat *tp_chat,
2512                  EmpathyChat   *chat)
2513 {
2514         EmpathyChatPriv *priv;
2515
2516         priv = GET_PRIV (chat);
2517
2518         if (!priv->tp_chat) {
2519                 return;
2520         }
2521
2522         chat_composing_remove_timeout (chat);
2523         g_object_unref (priv->tp_chat);
2524         priv->tp_chat = NULL;
2525         g_object_notify (G_OBJECT (chat), "tp-chat");
2526
2527         empathy_chat_view_append_event (chat->view, _("Disconnected"));
2528         gtk_widget_set_sensitive (chat->input_text_view, FALSE);
2529
2530         chat_update_contacts_visibility (chat, FALSE);
2531 }
2532
2533 static gboolean
2534 update_misspelled_words (gpointer data)
2535 {
2536         EmpathyChat *chat = EMPATHY_CHAT (data);
2537         EmpathyChatPriv *priv = GET_PRIV (chat);
2538         GtkTextBuffer *buffer;
2539         GtkTextIter iter;
2540         gint length;
2541
2542         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2543
2544         gtk_text_buffer_get_end_iter (buffer, &iter);
2545         length = gtk_text_iter_get_offset (&iter);
2546         chat_input_text_buffer_insert_text_cb (buffer, &iter,
2547                                                NULL, length, chat);
2548
2549         priv->update_misspelled_words_id = 0;
2550
2551         return FALSE;
2552 }
2553
2554 static void
2555 conf_spell_checking_cb (GSettings *gsettings_chat,
2556                         const gchar *key,
2557                         gpointer user_data)
2558 {
2559         EmpathyChat *chat = EMPATHY_CHAT (user_data);
2560         EmpathyChatPriv *priv = GET_PRIV (chat);
2561         gboolean spell_checker;
2562         GtkTextBuffer *buffer;
2563
2564         if (strcmp (key, EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED) != 0)
2565                 return;
2566
2567         spell_checker = g_settings_get_boolean (gsettings_chat,
2568                         EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED);
2569
2570         if (!empathy_spell_supported ()) {
2571                 spell_checker = FALSE;
2572         }
2573
2574         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2575
2576         if (spell_checker == priv->spell_checking_enabled) {
2577                 if (spell_checker) {
2578                         /* Possibly changed dictionaries,
2579                          * update misspelled words. Need to do so in idle
2580                          * so the spell checker is updated. */
2581                         priv->update_misspelled_words_id =
2582                                 g_idle_add (update_misspelled_words, chat);
2583                 }
2584
2585                 return;
2586         }
2587
2588         if (spell_checker) {
2589                 GtkTextIter iter;
2590
2591                 priv->notify_cursor_position_id = tp_g_signal_connect_object  (
2592                                 buffer, "notify::cursor-position",
2593                                 G_CALLBACK (chat_input_text_buffer_notify_cursor_position_cb),
2594                                 chat, 0);
2595                 priv->insert_text_id = tp_g_signal_connect_object  (
2596                                 buffer, "insert-text",
2597                                 G_CALLBACK (chat_input_text_buffer_insert_text_cb),
2598                                 chat, G_CONNECT_AFTER);
2599                 priv->delete_range_id = tp_g_signal_connect_object  (
2600                                 buffer, "delete-range",
2601                                 G_CALLBACK (chat_input_text_buffer_delete_range_cb),
2602                                 chat, G_CONNECT_AFTER);
2603
2604                 gtk_text_buffer_create_tag (buffer, "misspelled",
2605                                             "underline", PANGO_UNDERLINE_ERROR,
2606                                             NULL);
2607
2608                 gtk_text_buffer_get_iter_at_mark (buffer, &iter,
2609                                                   gtk_text_buffer_get_insert (buffer));
2610                 gtk_text_buffer_create_mark (buffer, "previous-cursor-position",
2611                                              &iter, TRUE);
2612
2613                 /* Mark misspelled words in the existing buffer.
2614                  * Need to do so in idle so the spell checker is updated. */
2615                 priv->update_misspelled_words_id =
2616                         g_idle_add (update_misspelled_words, chat);
2617         } else {
2618                 GtkTextTagTable *table;
2619                 GtkTextTag *tag;
2620
2621                 g_signal_handler_disconnect (buffer, priv->notify_cursor_position_id);
2622                 priv->notify_cursor_position_id = 0;
2623                 g_signal_handler_disconnect (buffer, priv->insert_text_id);
2624                 priv->insert_text_id = 0;
2625                 g_signal_handler_disconnect (buffer, priv->delete_range_id);
2626                 priv->delete_range_id = 0;
2627
2628                 table = gtk_text_buffer_get_tag_table (buffer);
2629                 tag = gtk_text_tag_table_lookup (table, "misspelled");
2630                 gtk_text_tag_table_remove (table, tag);
2631
2632                 gtk_text_buffer_delete_mark_by_name (buffer,
2633                                                      "previous-cursor-position");
2634         }
2635
2636         priv->spell_checking_enabled = spell_checker;
2637 }
2638
2639 static gboolean
2640 save_paned_pos_timeout (gpointer data)
2641 {
2642         EmpathyChat *self = data;
2643         gint hpaned_pos;
2644
2645         hpaned_pos = gtk_paned_get_position (GTK_PANED (self->priv->hpaned));
2646
2647         g_settings_set_int (self->priv->gsettings_ui,
2648                             EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS,
2649                             hpaned_pos);
2650
2651         return FALSE;
2652 }
2653
2654 static gboolean
2655 chat_hpaned_pos_changed_cb (GtkWidget* hpaned,
2656                 GParamSpec *spec,
2657                 gpointer user_data)
2658 {
2659         EmpathyChat *chat = EMPATHY_CHAT (user_data);
2660
2661         if (chat->priv->save_paned_pos_id != 0)
2662                 g_source_remove (chat->priv->save_paned_pos_id);
2663
2664         chat->priv->save_paned_pos_id = g_timeout_add_seconds (1,
2665                 save_paned_pos_timeout, chat);
2666
2667         return TRUE;
2668 }
2669
2670 static void
2671 chat_create_ui (EmpathyChat *chat)
2672 {
2673         EmpathyChatPriv *priv = GET_PRIV (chat);
2674         GtkBuilder      *gui;
2675         GList           *list = NULL;
2676         gchar           *filename;
2677         GtkTextBuffer   *buffer;
2678         gint              paned_pos;
2679         EmpathyThemeManager *theme_mgr;
2680
2681         filename = empathy_file_lookup ("empathy-chat.ui",
2682                                         "libempathy-gtk");
2683         gui = empathy_builder_get_file (filename,
2684                                         "chat_widget", &priv->widget,
2685                                         "hpaned", &priv->hpaned,
2686                                         "vbox_left", &priv->vbox_left,
2687                                         "scrolled_window_chat", &priv->scrolled_window_chat,
2688                                         "scrolled_window_input", &priv->scrolled_window_input,
2689                                         "hbox_topic", &priv->hbox_topic,
2690                                         "expander_topic", &priv->expander_topic,
2691                                         "label_topic", &priv->label_topic,
2692                                         "scrolled_window_contacts", &priv->scrolled_window_contacts,
2693                                         "info_bar_vbox", &priv->info_bar_vbox,
2694                                         NULL);
2695
2696         empathy_builder_connect (gui, chat,
2697                 "expander_topic", "notify::expanded", chat_topic_expander_activate_cb,
2698                 "label_topic", "size-allocate", chat_topic_label_size_allocate_cb,
2699                 NULL);
2700
2701         g_free (filename);
2702
2703         /* Add message view. */
2704         theme_mgr = empathy_theme_manager_dup_singleton ();
2705         chat->view = empathy_theme_manager_create_view (theme_mgr);
2706         g_object_unref (theme_mgr);
2707         /* If this is a GtkTextView, it's set as a drag destination for text/plain
2708            and other types, even though it's non-editable and doesn't accept any
2709            drags.  This steals drag motion for anything inside the scrollbars,
2710            making drag destinations on chat windows far less useful.
2711          */
2712         gtk_drag_dest_unset (GTK_WIDGET (chat->view));
2713         g_signal_connect (chat->view, "focus_in_event",
2714                           G_CALLBACK (chat_text_view_focus_in_event_cb),
2715                           chat);
2716         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_chat),
2717                            GTK_WIDGET (chat->view));
2718         gtk_widget_show (GTK_WIDGET (chat->view));
2719
2720         /* Add input GtkTextView */
2721         chat->input_text_view = empathy_input_text_view_new ();
2722         g_signal_connect (chat->input_text_view, "notify::has-focus",
2723                           G_CALLBACK (chat_input_has_focus_notify_cb),
2724                           chat);
2725         g_signal_connect (chat->input_text_view, "key-press-event",
2726                           G_CALLBACK (chat_input_key_press_event_cb),
2727                           chat);
2728         g_signal_connect (chat->input_text_view, "realize",
2729                           G_CALLBACK (chat_input_realize_cb),
2730                           chat);
2731         g_signal_connect (chat->input_text_view, "populate-popup",
2732                           G_CALLBACK (chat_input_populate_popup_cb),
2733                           chat);
2734         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2735         tp_g_signal_connect_object  (buffer, "changed",
2736                           G_CALLBACK (chat_input_text_buffer_changed_cb),
2737                           chat, 0);
2738         tp_g_signal_connect_object (priv->gsettings_chat,
2739                         "changed::" EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED,
2740                         G_CALLBACK (conf_spell_checking_cb), chat, 0);
2741         conf_spell_checking_cb (priv->gsettings_chat,
2742                                 EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED, chat);
2743         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_input),
2744                            chat->input_text_view);
2745         gtk_widget_show (chat->input_text_view);
2746
2747         /* Add the (invisible) search bar */
2748         priv->search_bar = empathy_search_bar_new (chat->view);
2749         gtk_box_pack_start (GTK_BOX(priv->vbox_left),
2750                             priv->search_bar,
2751                             FALSE, FALSE, 0);
2752         gtk_box_reorder_child (GTK_BOX(priv->vbox_left), priv->search_bar, 1);
2753
2754         /* Initialy hide the topic, will be shown if not empty */
2755         gtk_widget_hide (priv->hbox_topic);
2756
2757         g_signal_connect (priv->hpaned, "notify::position",
2758                           G_CALLBACK (chat_hpaned_pos_changed_cb),
2759                           chat);
2760
2761         /* Load the paned position */
2762         paned_pos = g_settings_get_int (priv->gsettings_ui,
2763                         EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS);
2764         if (paned_pos != 0)
2765                 gtk_paned_set_position (GTK_PANED(priv->hpaned), paned_pos);
2766
2767         /* Set widget focus order */
2768         list = g_list_append (NULL, priv->search_bar);
2769         list = g_list_append (list, priv->scrolled_window_input);
2770         gtk_container_set_focus_chain (GTK_CONTAINER (priv->vbox_left), list);
2771         g_list_free (list);
2772
2773         list = g_list_append (NULL, priv->vbox_left);
2774         list = g_list_append (list, priv->scrolled_window_contacts);
2775         gtk_container_set_focus_chain (GTK_CONTAINER (priv->hpaned), list);
2776         g_list_free (list);
2777
2778         list = g_list_append (NULL, priv->hpaned);
2779         list = g_list_append (list, priv->hbox_topic);
2780         gtk_container_set_focus_chain (GTK_CONTAINER (priv->widget), list);
2781         g_list_free (list);
2782
2783         /* Add the main widget in the chat widget */
2784         gtk_container_add (GTK_CONTAINER (chat), priv->widget);
2785         g_object_unref (gui);
2786 }
2787
2788 static void
2789 chat_size_allocate (GtkWidget     *widget,
2790                     GtkAllocation *allocation)
2791 {
2792   GtkBin *bin = GTK_BIN (widget);
2793   GtkAllocation child_allocation;
2794   GtkWidget *child;
2795
2796   gtk_widget_set_allocation (widget, allocation);
2797
2798   child = gtk_bin_get_child (bin);
2799
2800   if (child && gtk_widget_get_visible (child))
2801     {
2802       child_allocation.x = allocation->x + gtk_container_get_border_width (GTK_CONTAINER (widget));
2803       child_allocation.y = allocation->y + gtk_container_get_border_width (GTK_CONTAINER (widget));
2804       child_allocation.width = MAX (allocation->width - gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2, 0);
2805       child_allocation.height = MAX (allocation->height - gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2, 0);
2806
2807       gtk_widget_size_allocate (child, &child_allocation);
2808     }
2809 }
2810
2811 static void
2812 chat_finalize (GObject *object)
2813 {
2814         EmpathyChat     *chat;
2815         EmpathyChatPriv *priv;
2816
2817         chat = EMPATHY_CHAT (object);
2818         priv = GET_PRIV (chat);
2819
2820         DEBUG ("Finalized: %p", object);
2821
2822         if (priv->update_misspelled_words_id != 0)
2823                 g_source_remove (priv->update_misspelled_words_id);
2824
2825         if (priv->save_paned_pos_id != 0)
2826                 g_source_remove (priv->save_paned_pos_id);
2827
2828         g_object_unref (priv->gsettings_chat);
2829         g_object_unref (priv->gsettings_ui);
2830
2831         g_list_foreach (priv->input_history, (GFunc) chat_input_history_entry_free, NULL);
2832         g_list_free (priv->input_history);
2833
2834         g_list_foreach (priv->compositors, (GFunc) g_object_unref, NULL);
2835         g_list_free (priv->compositors);
2836
2837         chat_composing_remove_timeout (chat);
2838
2839         g_object_unref (priv->account_manager);
2840         g_object_unref (priv->log_manager);
2841
2842         if (priv->tp_chat) {
2843                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2844                         chat_destroy_cb, chat);
2845                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2846                         chat_message_received_cb, chat);
2847                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2848                         chat_send_error_cb, chat);
2849                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2850                         chat_state_changed_cb, chat);
2851                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2852                         chat_property_changed_cb, chat);
2853                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2854                         chat_members_changed_cb, chat);
2855                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2856                         chat_remote_contact_changed_cb, chat);
2857                 empathy_tp_chat_leave (priv->tp_chat, "");
2858                 g_object_unref (priv->tp_chat);
2859         }
2860         if (priv->account) {
2861                 g_object_unref (priv->account);
2862         }
2863         if (priv->remote_contact) {
2864                 g_object_unref (priv->remote_contact);
2865         }
2866
2867         if (priv->block_events_timeout_id) {
2868                 g_source_remove (priv->block_events_timeout_id);
2869         }
2870
2871         g_free (priv->id);
2872         g_free (priv->name);
2873         g_free (priv->subject);
2874         g_completion_free (priv->completion);
2875
2876         G_OBJECT_CLASS (empathy_chat_parent_class)->finalize (object);
2877 }
2878
2879 static void
2880 chat_constructed (GObject *object)
2881 {
2882         EmpathyChat *chat = EMPATHY_CHAT (object);
2883         EmpathyChatPriv *priv = GET_PRIV (chat);
2884
2885         if (priv->handle_type != TP_HANDLE_TYPE_ROOM) {
2886                 /* First display logs from the logger and then display pending messages */
2887                 chat_add_logs (chat);
2888         }
2889          else {
2890                 /* Just display pending messages for rooms */
2891                 priv->can_show_pending = TRUE;
2892                 show_pending_messages (chat);
2893         }
2894 }
2895
2896 static void
2897 empathy_chat_class_init (EmpathyChatClass *klass)
2898 {
2899         GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
2900         GObjectClass   *object_class = G_OBJECT_CLASS (klass);
2901
2902         object_class->finalize = chat_finalize;
2903         object_class->get_property = chat_get_property;
2904         object_class->set_property = chat_set_property;
2905         object_class->constructed = chat_constructed;
2906
2907         widget_class->size_allocate = chat_size_allocate;
2908
2909         g_object_class_install_property (object_class,
2910                                          PROP_TP_CHAT,
2911                                          g_param_spec_object ("tp-chat",
2912                                                               "Empathy tp chat",
2913                                                               "The tp chat object",
2914                                                               EMPATHY_TYPE_TP_CHAT,
2915                                                               G_PARAM_CONSTRUCT |
2916                                                               G_PARAM_READWRITE |
2917                                                               G_PARAM_STATIC_STRINGS));
2918         g_object_class_install_property (object_class,
2919                                          PROP_ACCOUNT,
2920                                          g_param_spec_object ("account",
2921                                                               "Account of the chat",
2922                                                               "The account of the chat",
2923                                                               TP_TYPE_ACCOUNT,
2924                                                               G_PARAM_READABLE |
2925                                                               G_PARAM_STATIC_STRINGS));
2926         g_object_class_install_property (object_class,
2927                                          PROP_ID,
2928                                          g_param_spec_string ("id",
2929                                                               "Chat's id",
2930                                                               "The id of the chat",
2931                                                               NULL,
2932                                                               G_PARAM_READABLE |
2933                                                               G_PARAM_STATIC_STRINGS));
2934         g_object_class_install_property (object_class,
2935                                          PROP_NAME,
2936                                          g_param_spec_string ("name",
2937                                                               "Chat's name",
2938                                                               "The name of the chat",
2939                                                               NULL,
2940                                                               G_PARAM_READABLE |
2941                                                               G_PARAM_STATIC_STRINGS));
2942         g_object_class_install_property (object_class,
2943                                          PROP_SUBJECT,
2944                                          g_param_spec_string ("subject",
2945                                                               "Chat's subject",
2946                                                               "The subject or topic of the chat",
2947                                                               NULL,
2948                                                               G_PARAM_READABLE |
2949                                                               G_PARAM_STATIC_STRINGS));
2950         g_object_class_install_property (object_class,
2951                                          PROP_REMOTE_CONTACT,
2952                                          g_param_spec_object ("remote-contact",
2953                                                               "The remote contact",
2954                                                               "The remote contact is any",
2955                                                               EMPATHY_TYPE_CONTACT,
2956                                                               G_PARAM_READABLE |
2957                                                               G_PARAM_STATIC_STRINGS));
2958         g_object_class_install_property (object_class,
2959                                          PROP_SHOW_CONTACTS,
2960                                          g_param_spec_boolean ("show-contacts",
2961                                                                "Contacts' visibility",
2962                                                                "The visibility of the contacts' list",
2963                                                                TRUE,
2964                                                                G_PARAM_READWRITE |
2965                                                                G_PARAM_STATIC_STRINGS));
2966
2967         g_object_class_install_property (object_class,
2968                                          PROP_SMS_CHANNEL,
2969                                          g_param_spec_boolean ("sms-channel",
2970                                                                "SMS Channel",
2971                                                                "TRUE if this channel is for sending SMSes",
2972                                                                FALSE,
2973                                                                G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
2974
2975         g_object_class_install_property (object_class,
2976                                          PROP_N_MESSAGES_SENDING,
2977                                          g_param_spec_uint ("n-messages-sending",
2978                                                             "Num Messages Sending",
2979                                                             "The number of messages being sent",
2980                                                             0, G_MAXUINT, 0,
2981                                                             G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
2982
2983         signals[COMPOSING] =
2984                 g_signal_new ("composing",
2985                               G_OBJECT_CLASS_TYPE (object_class),
2986                               G_SIGNAL_RUN_LAST,
2987                               0,
2988                               NULL, NULL,
2989                               g_cclosure_marshal_VOID__BOOLEAN,
2990                               G_TYPE_NONE,
2991                               1, G_TYPE_BOOLEAN);
2992
2993         signals[NEW_MESSAGE] =
2994                 g_signal_new ("new-message",
2995                               G_OBJECT_CLASS_TYPE (object_class),
2996                               G_SIGNAL_RUN_LAST,
2997                               0,
2998                               NULL, NULL,
2999                               _empathy_gtk_marshal_VOID__OBJECT_BOOLEAN,
3000                               G_TYPE_NONE,
3001                               2, EMPATHY_TYPE_MESSAGE, G_TYPE_BOOLEAN);
3002
3003         signals[PART_COMMAND_ENTERED] =
3004                         g_signal_new ("part-command-entered",
3005                                   G_OBJECT_CLASS_TYPE (object_class),
3006                                   G_SIGNAL_RUN_LAST,
3007                                   0,
3008                                   NULL, NULL,
3009                                   g_cclosure_marshal_VOID__POINTER,
3010                                   G_TYPE_NONE,
3011                                   1, G_TYPE_STRV);
3012
3013         g_type_class_add_private (object_class, sizeof (EmpathyChatPriv));
3014 }
3015
3016 static gboolean
3017 chat_block_events_timeout_cb (gpointer data)
3018 {
3019         EmpathyChatPriv *priv = GET_PRIV (data);
3020
3021         priv->block_events_timeout_id = 0;
3022
3023         return FALSE;
3024 }
3025
3026 static void
3027 account_manager_prepared_cb (GObject *source_object,
3028                              GAsyncResult *result,
3029                              gpointer user_data)
3030 {
3031         GList *accounts, *l;
3032         TpAccountManager *account_manager = TP_ACCOUNT_MANAGER (source_object);
3033         EmpathyChat *chat = user_data;
3034         GError *error = NULL;
3035
3036         if (!tp_account_manager_prepare_finish (account_manager, result, &error)) {
3037                 DEBUG ("Failed to prepare the account manager: %s", error->message);
3038                 g_error_free (error);
3039                 return;
3040         }
3041
3042         accounts = tp_account_manager_get_valid_accounts (account_manager);
3043
3044         for (l = accounts; l != NULL; l = l->next) {
3045                 TpAccount *account = l->data;
3046                 tp_g_signal_connect_object (account, "status-changed",
3047                                              G_CALLBACK (chat_new_connection_cb),
3048                                              chat, 0);
3049         }
3050
3051         g_list_free (accounts);
3052 }
3053
3054 static void
3055 empathy_chat_init (EmpathyChat *chat)
3056 {
3057         EmpathyChatPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chat,
3058                 EMPATHY_TYPE_CHAT, EmpathyChatPriv);
3059
3060         chat->priv = priv;
3061         priv->log_manager = tpl_log_manager_dup_singleton ();
3062         priv->gsettings_chat = g_settings_new (EMPATHY_PREFS_CHAT_SCHEMA);
3063         priv->gsettings_ui = g_settings_new (EMPATHY_PREFS_UI_SCHEMA);
3064
3065         priv->contacts_width = -1;
3066         priv->input_history = NULL;
3067         priv->input_history_current = NULL;
3068         priv->account_manager = tp_account_manager_dup ();
3069
3070         tp_account_manager_prepare_async (priv->account_manager, NULL,
3071                                           account_manager_prepared_cb, chat);
3072
3073         priv->show_contacts = g_settings_get_boolean (priv->gsettings_chat,
3074                         EMPATHY_PREFS_CHAT_SHOW_CONTACTS_IN_ROOMS);
3075
3076         /* Block events for some time to avoid having "has come online" or
3077          * "joined" messages. */
3078         priv->block_events_timeout_id =
3079                 g_timeout_add_seconds (1, chat_block_events_timeout_cb, chat);
3080
3081         /* Add nick name completion */
3082         priv->completion = g_completion_new ((GCompletionFunc) empathy_contact_get_alias);
3083         g_completion_set_compare (priv->completion, chat_contacts_completion_func);
3084
3085         chat_create_ui (chat);
3086 }
3087
3088 EmpathyChat *
3089 empathy_chat_new (EmpathyTpChat *tp_chat)
3090 {
3091         return g_object_new (EMPATHY_TYPE_CHAT, "tp-chat", tp_chat, NULL);
3092 }
3093
3094 EmpathyTpChat *
3095 empathy_chat_get_tp_chat (EmpathyChat *chat)
3096 {
3097         EmpathyChatPriv *priv = GET_PRIV (chat);
3098
3099         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3100
3101         return priv->tp_chat;
3102 }
3103
3104 typedef struct
3105 {
3106         EmpathyChat *self;
3107         GtkWidget *info_bar;
3108         gulong response_id;
3109         GtkWidget *button;
3110         GtkWidget *label;
3111         GtkWidget *entry;
3112         GtkWidget *spinner;
3113         gchar *password;
3114 } PasswordData;
3115
3116 static void
3117 passwd_remember_button_cb (GtkButton *button,
3118                           PasswordData *data)
3119 {
3120         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3121 }
3122
3123 static void
3124 passwd_not_now_button_cb (GtkButton *button,
3125                           PasswordData *data)
3126 {
3127         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_NO);
3128 }
3129
3130 static void
3131 remember_password_infobar_response_cb (GtkWidget *info_bar,
3132                                        gint response_id,
3133                                        PasswordData *data)
3134 {
3135         EmpathyChatPriv *priv = GET_PRIV (data->self);
3136
3137         if (response_id == GTK_RESPONSE_OK) {
3138                 DEBUG ("Saving room password");
3139                 empathy_keyring_set_room_password_async (priv->account,
3140                                                          empathy_tp_chat_get_id (priv->tp_chat),
3141                                                          data->password,
3142                                                          NULL, NULL);
3143         }
3144
3145         gtk_widget_destroy (info_bar);
3146         g_free (data->password);
3147         g_slice_free (PasswordData, data);
3148 }
3149
3150 static void
3151 chat_prompt_to_save_password (EmpathyChat *self,
3152                               PasswordData *data)
3153 {
3154         GtkWidget *content_area;
3155         GtkWidget *hbox;
3156         GtkWidget *image;
3157         GtkWidget *label;
3158         GtkWidget *alig;
3159         GtkWidget *button;
3160
3161         /* save the password in case it needs to be saved */
3162         data->password = g_strdup (gtk_entry_get_text (GTK_ENTRY (data->entry)));
3163
3164         /* Remove all previous widgets */
3165         content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (data->info_bar));
3166         gtk_container_forall (GTK_CONTAINER (content_area),
3167                               (GtkCallback) gtk_widget_destroy, NULL);
3168         data->button = NULL;
3169         data->label = NULL;
3170         data->entry = NULL;
3171         data->spinner = NULL;
3172
3173         gtk_info_bar_set_message_type (GTK_INFO_BAR (data->info_bar),
3174                                        GTK_MESSAGE_QUESTION);
3175
3176         hbox = gtk_hbox_new (FALSE, 5);
3177         gtk_box_pack_start (GTK_BOX (content_area), hbox, TRUE, TRUE, 0);
3178
3179         /* Add image */
3180         image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_AUTHENTICATION,
3181                                           GTK_ICON_SIZE_DIALOG);
3182         gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
3183
3184         /* Add message */
3185         label = gtk_label_new (_("Would you like to store this password?"));
3186         gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0);
3187
3188         /* Add 'Remember' button */
3189         alig = gtk_alignment_new (0, 0.5, 1, 0);
3190
3191         button = gtk_button_new_with_label (_("Remember"));
3192         gtk_container_add (GTK_CONTAINER (alig), button);
3193         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3194
3195         g_signal_connect (button, "clicked", G_CALLBACK (passwd_remember_button_cb),
3196                           data);
3197
3198         /* Add 'Not now' button */
3199         alig = gtk_alignment_new (0, 0.5, 1, 0);
3200
3201         button = gtk_button_new_with_label (_("Not now"));
3202         gtk_container_add (GTK_CONTAINER (alig), button);
3203         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3204
3205         g_signal_connect (button, "clicked", G_CALLBACK (passwd_not_now_button_cb),
3206                           data);
3207
3208         /* go! */
3209         g_signal_handler_disconnect (data->info_bar, data->response_id);
3210         g_signal_connect (data->info_bar, "response",
3211                           G_CALLBACK (remember_password_infobar_response_cb), data);
3212
3213         gtk_widget_show_all (data->info_bar);
3214 }
3215
3216 static void
3217 provide_password_cb (GObject *tp_chat,
3218                      GAsyncResult *res,
3219                      gpointer user_data)
3220 {
3221         PasswordData *data = user_data;
3222         EmpathyChat *self = data->self;
3223         EmpathyChatPriv *priv = GET_PRIV (self);
3224         GError *error = NULL;
3225
3226         if (!empathy_tp_chat_provide_password_finish (EMPATHY_TP_CHAT (tp_chat), res,
3227                                                       &error)) {
3228                 DEBUG ("error: %s", error->message);
3229                 /* FIXME: what should we do if that's another error? Close the channel?
3230                  * Display the raw D-Bus error to the user isn't very useful */
3231                 if (g_error_matches (error, TP_ERRORS, TP_ERROR_AUTHENTICATION_FAILED)) {
3232                         /* entry */
3233                         gtk_entry_set_text (GTK_ENTRY (data->entry), "");
3234                         gtk_widget_set_sensitive (data->entry, TRUE);
3235                         gtk_widget_grab_focus (data->entry);
3236
3237                         /* info bar */
3238                         gtk_info_bar_set_message_type (
3239                             GTK_INFO_BAR (data->info_bar),
3240                             GTK_MESSAGE_ERROR);
3241
3242                         /* button */
3243                         gtk_widget_set_sensitive (data->button, TRUE);
3244                         gtk_button_set_label (GTK_BUTTON (data->button),
3245                             _("Retry"));
3246
3247                         /* label */
3248                         gtk_label_set_text (GTK_LABEL (data->label),
3249                             _("Wrong password; please try again:"));
3250
3251                         /* spinner */
3252                         gtk_spinner_stop (GTK_SPINNER (data->spinner));
3253                         gtk_widget_hide (data->spinner);
3254                 }
3255                 g_error_free (error);
3256                 return;
3257         }
3258
3259         if (empathy_keyring_is_available ()) {
3260                 /* ask whether they want to save the password */
3261                 chat_prompt_to_save_password (self, data);
3262         } else {
3263                 /* Get rid of the password info bar finally */
3264                 gtk_widget_destroy (data->info_bar);
3265                 g_slice_free (PasswordData, data);
3266         }
3267
3268         /* Room joined */
3269         gtk_widget_set_sensitive (priv->hpaned, TRUE);
3270         gtk_widget_grab_focus (self->input_text_view);
3271 }
3272
3273 static void
3274 password_infobar_response_cb (GtkWidget *info_bar,
3275                               gint response_id,
3276                               PasswordData *data)
3277 {
3278         EmpathyChatPriv *priv = GET_PRIV (data->self);
3279         const gchar *password;
3280
3281         if (response_id != GTK_RESPONSE_OK) {
3282                 gtk_widget_destroy (info_bar);
3283                 g_slice_free (PasswordData, data);
3284                 return;
3285         }
3286
3287         password = gtk_entry_get_text (GTK_ENTRY (data->entry));
3288
3289         empathy_tp_chat_provide_password_async (priv->tp_chat, password,
3290                                                 provide_password_cb, data);
3291
3292         gtk_widget_set_sensitive (data->button, FALSE);
3293         gtk_widget_set_sensitive (data->entry, FALSE);
3294
3295         gtk_spinner_start (GTK_SPINNER (data->spinner));
3296         gtk_widget_show (data->spinner);
3297 }
3298
3299 static void
3300 password_entry_activate_cb (GtkWidget *entry,
3301                           PasswordData *data)
3302 {
3303         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3304 }
3305
3306 static void
3307 passwd_join_button_cb (GtkButton *button,
3308                           PasswordData *data)
3309 {
3310         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3311 }
3312
3313 static void
3314 clear_icon_released_cb (GtkEntry *entry,
3315                         GtkEntryIconPosition icon_pos,
3316                         GdkEvent *event,
3317                         PasswordData *data)
3318 {
3319         gtk_entry_set_text (entry, "");
3320 }
3321
3322 static void
3323 password_entry_changed_cb (GtkEditable *entry,
3324                            PasswordData *data)
3325 {
3326         const gchar *str;
3327
3328         str = gtk_entry_get_text (GTK_ENTRY (entry));
3329
3330         gtk_entry_set_icon_sensitive (GTK_ENTRY (entry),
3331             GTK_ENTRY_ICON_SECONDARY, !EMP_STR_EMPTY (str));
3332 }
3333
3334 static void
3335 chat_invalidated_cb (TpProxy       *proxy,
3336                            guint          domain,
3337                            gint           code,
3338                            gchar         *message,
3339                            gpointer       password_infobar)
3340 {
3341         /* Destroy the password infobar whenever a channel is invalidated
3342          * so we don't have multiple infobars when the MUC is rejoined */
3343         gtk_widget_destroy (GTK_WIDGET (password_infobar));
3344 }
3345
3346 static void
3347 display_password_info_bar (EmpathyChat *self)
3348 {
3349         EmpathyChatPriv *priv = GET_PRIV (self);
3350         GtkWidget *info_bar;
3351         GtkWidget *content_area;
3352         GtkWidget *hbox;
3353         GtkWidget *image;
3354         GtkWidget *label;
3355         GtkWidget *entry;
3356         GtkWidget *alig;
3357         GtkWidget *button;
3358         GtkWidget *spinner;
3359         PasswordData *data;
3360
3361         data = g_slice_new0 (PasswordData);
3362
3363         info_bar = gtk_info_bar_new ();
3364         gtk_info_bar_set_message_type (GTK_INFO_BAR (info_bar),
3365             GTK_MESSAGE_QUESTION);
3366
3367         content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (info_bar));
3368
3369         hbox = gtk_hbox_new (FALSE, 5);
3370         gtk_box_pack_start (GTK_BOX (content_area), hbox, TRUE, TRUE, 0);
3371
3372         /* Add image */
3373         image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_AUTHENTICATION,
3374                                           GTK_ICON_SIZE_DIALOG);
3375         gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
3376
3377         /* Add message */
3378         label = gtk_label_new (_("This room is protected by a password:"));
3379         gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);
3380
3381         /* Add password entry */
3382         entry = gtk_entry_new ();
3383         gtk_entry_set_visibility (GTK_ENTRY (entry), FALSE);
3384         gtk_box_pack_start (GTK_BOX (hbox), entry, TRUE, TRUE, 0);
3385
3386         gtk_entry_set_icon_from_stock (GTK_ENTRY (entry),
3387                                        GTK_ENTRY_ICON_SECONDARY, GTK_STOCK_CLEAR);
3388         gtk_entry_set_icon_sensitive (GTK_ENTRY (entry),
3389                                       GTK_ENTRY_ICON_SECONDARY, FALSE);
3390
3391         g_signal_connect (entry, "icon-release",
3392                           G_CALLBACK (clear_icon_released_cb), data);
3393         g_signal_connect (entry, "changed",
3394                           G_CALLBACK (password_entry_changed_cb), data);
3395
3396         g_signal_connect (entry, "activate",
3397                           G_CALLBACK (password_entry_activate_cb), data);
3398
3399         /* Focus the password entry once it's realized */
3400         g_signal_connect (entry, "realize", G_CALLBACK (gtk_widget_grab_focus), NULL);
3401
3402         /* Add 'Join' button */
3403         alig = gtk_alignment_new (0, 0.5, 1, 0);
3404
3405         button = gtk_button_new_with_label (_("Join"));
3406         gtk_container_add (GTK_CONTAINER (alig), button);
3407         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3408
3409         g_signal_connect (button, "clicked", G_CALLBACK (passwd_join_button_cb),
3410                           data);
3411
3412         /* Add spinner */
3413         spinner = gtk_spinner_new ();
3414         gtk_box_pack_end (GTK_BOX (hbox), spinner, FALSE, FALSE, 0);
3415
3416         /* Save some data for messing around with later */
3417         data->self = self;
3418         data->info_bar = info_bar;
3419         data->button = button;
3420         data->label = label;
3421         data->entry = entry;
3422         data->spinner = spinner;
3423
3424         gtk_box_pack_start (GTK_BOX (priv->info_bar_vbox), info_bar,
3425                             TRUE, TRUE, 3);
3426         gtk_widget_show_all (hbox);
3427
3428         tp_g_signal_connect_object (empathy_tp_chat_get_channel (priv->tp_chat),
3429                                   "invalidated", G_CALLBACK (chat_invalidated_cb),
3430                                   info_bar, 0);
3431
3432         data->response_id = g_signal_connect (info_bar, "response",
3433                                               G_CALLBACK (password_infobar_response_cb), data);
3434
3435         gtk_widget_show_all (info_bar);
3436         /* ... but hide the spinner */
3437         gtk_widget_hide (spinner);
3438
3439         /* prevent the user from typing anything */
3440         gtk_widget_set_sensitive (self->input_text_view, FALSE);
3441 }
3442
3443 static void
3444 provide_saved_password_cb (GObject *tp_chat,
3445                            GAsyncResult *res,
3446                            gpointer user_data)
3447 {
3448         EmpathyChat *self = user_data;
3449         EmpathyChatPriv *priv = GET_PRIV (self);
3450         GError *error = NULL;
3451
3452         if (!empathy_tp_chat_provide_password_finish (EMPATHY_TP_CHAT (tp_chat), res,
3453                                                       &error)) {
3454                 DEBUG ("error: %s", error->message);
3455                 /* FIXME: what should we do if that's another error? Close the channel?
3456                  * Display the raw D-Bus error to the user isn't very useful */
3457                 if (g_error_matches (error, TP_ERRORS, TP_ERROR_AUTHENTICATION_FAILED)) {
3458                         display_password_info_bar (self);
3459                         gtk_widget_set_sensitive (priv->hpaned, FALSE);
3460                 }
3461                 g_error_free (error);
3462                 return;
3463         }
3464
3465         /* Room joined */
3466         gtk_widget_set_sensitive (priv->hpaned, TRUE);
3467         gtk_widget_grab_focus (self->input_text_view);
3468 }
3469
3470 static void
3471 chat_room_got_password_cb (GObject *source,
3472                            GAsyncResult *result,
3473                            gpointer user_data)
3474 {
3475         EmpathyChat *self = user_data;
3476         EmpathyChatPriv *priv = GET_PRIV (self);
3477         const gchar *password;
3478         GError *error = NULL;
3479
3480         password = empathy_keyring_get_room_password_finish (priv->account,
3481             result, &error);
3482
3483         if (error != NULL) {
3484                 DEBUG ("Couldn't get room password: %s\n", error->message);
3485                 g_clear_error (&error);
3486
3487                 display_password_info_bar (self);
3488                 gtk_widget_set_sensitive (priv->hpaned, FALSE);
3489                 return;
3490         }
3491
3492         empathy_tp_chat_provide_password_async (priv->tp_chat, password,
3493                                                 provide_saved_password_cb, self);
3494 }
3495
3496 static void
3497 chat_password_needed_changed_cb (EmpathyChat *self)
3498 {
3499         EmpathyChatPriv *priv = GET_PRIV (self);
3500
3501         if (empathy_tp_chat_password_needed (priv->tp_chat)) {
3502                 empathy_keyring_get_room_password_async (priv->account,
3503                                                          empathy_tp_chat_get_id (priv->tp_chat),
3504                                                          chat_room_got_password_cb, self);
3505         }
3506 }
3507
3508 static void
3509 chat_sms_channel_changed_cb (EmpathyChat *self)
3510 {
3511         EmpathyChatPriv *priv = GET_PRIV (self);
3512
3513         priv->sms_channel = empathy_tp_chat_is_sms_channel (priv->tp_chat);
3514         g_object_notify (G_OBJECT (self), "sms-channel");
3515 }
3516
3517 static void
3518 chat_n_messages_sending_changed_cb (EmpathyChat *self)
3519 {
3520         g_object_notify (G_OBJECT (self), "n-messages-sending");
3521 }
3522
3523 void
3524 empathy_chat_set_tp_chat (EmpathyChat   *chat,
3525                           EmpathyTpChat *tp_chat)
3526 {
3527         EmpathyChatPriv *priv = GET_PRIV (chat);
3528         GPtrArray       *properties;
3529
3530         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3531         g_return_if_fail (EMPATHY_IS_TP_CHAT (tp_chat));
3532         g_return_if_fail (empathy_tp_chat_is_ready (tp_chat));
3533
3534         if (priv->tp_chat) {
3535                 return;
3536         }
3537
3538         if (priv->account) {
3539                 g_object_unref (priv->account);
3540         }
3541
3542         priv->tp_chat = g_object_ref (tp_chat);
3543         priv->account = g_object_ref (empathy_tp_chat_get_account (priv->tp_chat));
3544
3545         g_signal_connect (tp_chat, "destroy",
3546                           G_CALLBACK (chat_destroy_cb),
3547                           chat);
3548         g_signal_connect (tp_chat, "message-received",
3549                           G_CALLBACK (chat_message_received_cb),
3550                           chat);
3551         g_signal_connect (tp_chat, "send-error",
3552                           G_CALLBACK (chat_send_error_cb),
3553                           chat);
3554         g_signal_connect (tp_chat, "chat-state-changed",
3555                           G_CALLBACK (chat_state_changed_cb),
3556                           chat);
3557         g_signal_connect (tp_chat, "property-changed",
3558                           G_CALLBACK (chat_property_changed_cb),
3559                           chat);
3560         g_signal_connect (tp_chat, "members-changed",
3561                           G_CALLBACK (chat_members_changed_cb),
3562                           chat);
3563         g_signal_connect (tp_chat, "member-renamed",
3564                           G_CALLBACK (chat_member_renamed_cb),
3565                           chat);
3566         g_signal_connect_swapped (tp_chat, "notify::remote-contact",
3567                                   G_CALLBACK (chat_remote_contact_changed_cb),
3568                                   chat);
3569         g_signal_connect_swapped (tp_chat, "notify::password-needed",
3570                                   G_CALLBACK (chat_password_needed_changed_cb),
3571                                   chat);
3572         g_signal_connect_swapped (tp_chat, "notify::sms-channel",
3573                                   G_CALLBACK (chat_sms_channel_changed_cb),
3574                                   chat);
3575         g_signal_connect_swapped (tp_chat, "notify::n-messages-sending",
3576                                   G_CALLBACK (chat_n_messages_sending_changed_cb),
3577                                   chat);
3578
3579         /* Get initial value of properties */
3580         properties = empathy_tp_chat_get_properties (priv->tp_chat);
3581         if (properties != NULL) {
3582                 guint i;
3583
3584                 for (i = 0; i < properties->len; i++) {
3585                         EmpathyTpChatProperty *property;
3586
3587                         property = g_ptr_array_index (properties, i);
3588                         if (property->value == NULL)
3589                                 continue;
3590
3591                         chat_property_changed_cb (priv->tp_chat,
3592                                                   property->name,
3593                                                   property->value,
3594                                                   chat);
3595                 }
3596         }
3597
3598         chat_sms_channel_changed_cb (chat);
3599         chat_remote_contact_changed_cb (chat);
3600
3601         if (chat->input_text_view) {
3602                 gtk_widget_set_sensitive (chat->input_text_view, TRUE);
3603                 if (priv->block_events_timeout_id == 0) {
3604                         empathy_chat_view_append_event (chat->view, _("Connected"));
3605                 }
3606         }
3607
3608         g_object_notify (G_OBJECT (chat), "tp-chat");
3609         g_object_notify (G_OBJECT (chat), "id");
3610         g_object_notify (G_OBJECT (chat), "account");
3611
3612         /* This is a noop when tp-chat is set at object construction time and causes
3613          * the pending messages to be show when it's set on the object after it has
3614          * been created */
3615         show_pending_messages (chat);
3616
3617         /* check if a password is needed */
3618         chat_password_needed_changed_cb (chat);
3619 }
3620
3621 TpAccount *
3622 empathy_chat_get_account (EmpathyChat *chat)
3623 {
3624         EmpathyChatPriv *priv = GET_PRIV (chat);
3625
3626         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3627
3628         return priv->account;
3629 }
3630
3631 const gchar *
3632 empathy_chat_get_id (EmpathyChat *chat)
3633 {
3634         EmpathyChatPriv *priv = GET_PRIV (chat);
3635
3636         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3637
3638         return priv->id;
3639 }
3640
3641 gchar *
3642 empathy_chat_dup_name (EmpathyChat *chat)
3643 {
3644         EmpathyChatPriv *priv = GET_PRIV (chat);
3645         const gchar *ret;
3646
3647         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3648
3649         ret = priv->name;
3650
3651         if (!ret && priv->remote_contact) {
3652                 ret = empathy_contact_get_alias (priv->remote_contact);
3653         }
3654
3655         if (!ret)
3656                 ret = priv->id;
3657
3658         if (!ret)
3659                 ret = _("Conversation");
3660
3661         if (priv->sms_channel)
3662                 /* Translators: this string is a something like
3663                  * "Escher Cat (SMS)" */
3664                 return g_strdup_printf (_("%s (SMS)"), ret);
3665         else
3666                 return g_strdup (ret);
3667 }
3668
3669 const gchar *
3670 empathy_chat_get_subject (EmpathyChat *chat)
3671 {
3672         EmpathyChatPriv *priv = GET_PRIV (chat);
3673
3674         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3675
3676         return priv->subject;
3677 }
3678
3679 EmpathyContact *
3680 empathy_chat_get_remote_contact (EmpathyChat *chat)
3681 {
3682         EmpathyChatPriv *priv = GET_PRIV (chat);
3683
3684         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3685
3686         return priv->remote_contact;
3687 }
3688
3689 GtkWidget *
3690 empathy_chat_get_contact_menu (EmpathyChat *chat)
3691 {
3692         EmpathyChatPriv *priv = GET_PRIV (chat);
3693         GtkWidget       *menu = NULL;
3694
3695         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3696
3697         if (priv->remote_contact) {
3698                 menu = empathy_contact_menu_new (priv->remote_contact,
3699                                                  EMPATHY_CONTACT_FEATURE_CALL |
3700                                                  EMPATHY_CONTACT_FEATURE_LOG |
3701                                                  EMPATHY_CONTACT_FEATURE_INFO |
3702                                                  EMPATHY_CONTACT_FEATURE_BLOCK);
3703         }
3704
3705         return menu;
3706 }
3707
3708 void
3709 empathy_chat_clear (EmpathyChat *chat)
3710 {
3711         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3712
3713         empathy_chat_view_clear (chat->view);
3714 }
3715
3716 void
3717 empathy_chat_scroll_down (EmpathyChat *chat)
3718 {
3719         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3720
3721         empathy_chat_view_scroll_down (chat->view);
3722 }
3723
3724 void
3725 empathy_chat_cut (EmpathyChat *chat)
3726 {
3727         GtkTextBuffer *buffer;
3728
3729         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3730
3731         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3732         if (gtk_text_buffer_get_has_selection (buffer)) {
3733                 GtkClipboard *clipboard;
3734
3735                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3736
3737                 gtk_text_buffer_cut_clipboard (buffer, clipboard, TRUE);
3738         }
3739 }
3740
3741 void
3742 empathy_chat_copy (EmpathyChat *chat)
3743 {
3744         GtkTextBuffer *buffer;
3745
3746         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3747
3748         if (empathy_chat_view_get_has_selection (chat->view)) {
3749                 empathy_chat_view_copy_clipboard (chat->view);
3750                 return;
3751         }
3752
3753         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3754         if (gtk_text_buffer_get_has_selection (buffer)) {
3755                 GtkClipboard *clipboard;
3756
3757                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3758
3759                 gtk_text_buffer_copy_clipboard (buffer, clipboard);
3760         }
3761         else {
3762                 gint start_offset;
3763                 gint end_offset;
3764                 EmpathyChatPriv *priv = GET_PRIV (chat);
3765
3766                 if (gtk_label_get_selection_bounds (GTK_LABEL (priv->label_topic),
3767                                                                &start_offset,
3768                                                                &end_offset)) {
3769                         gchar *start;
3770                         gchar *end;
3771                         gchar *selection;
3772                         const gchar *topic;
3773                         GtkClipboard *clipboard;
3774
3775                         topic = gtk_label_get_text (GTK_LABEL (priv->label_topic));
3776                         start = g_utf8_offset_to_pointer (topic, start_offset);
3777                         end = g_utf8_offset_to_pointer (topic, end_offset);
3778                         selection = g_strndup (start, end - start);
3779
3780                         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3781                         gtk_clipboard_set_text (clipboard, selection, -1);
3782
3783                         g_free (selection);
3784                 }
3785         }
3786 }
3787
3788 void
3789 empathy_chat_paste (EmpathyChat *chat)
3790 {
3791         GtkTextBuffer *buffer;
3792         GtkClipboard  *clipboard;
3793         EmpathyChatPriv *priv;
3794
3795         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3796
3797         priv = GET_PRIV (chat);
3798
3799         if (gtk_widget_get_visible (priv->search_bar)) {
3800                 empathy_search_bar_paste_clipboard (EMPATHY_SEARCH_BAR (priv->search_bar));
3801                 return;
3802         }
3803
3804         if (priv->tp_chat == NULL ||
3805             !gtk_widget_is_sensitive (chat->input_text_view))
3806                 return;
3807
3808         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3809         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3810
3811         gtk_text_buffer_paste_clipboard (buffer, clipboard, NULL, TRUE);
3812 }
3813
3814 void
3815 empathy_chat_find (EmpathyChat *chat)
3816 {
3817         EmpathyChatPriv *priv;
3818
3819         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3820
3821         priv = GET_PRIV (chat);
3822
3823         empathy_search_bar_show (EMPATHY_SEARCH_BAR (priv->search_bar));
3824 }
3825
3826 void
3827 empathy_chat_correct_word (EmpathyChat  *chat,
3828                           GtkTextIter *start,
3829                           GtkTextIter *end,
3830                           const gchar *new_word)
3831 {
3832         GtkTextBuffer *buffer;
3833
3834         g_return_if_fail (chat != NULL);
3835         g_return_if_fail (new_word != NULL);
3836
3837         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3838
3839         gtk_text_buffer_delete (buffer, start, end);
3840         gtk_text_buffer_insert (buffer, start,
3841                                 new_word,
3842                                 -1);
3843 }
3844
3845 gboolean
3846 empathy_chat_is_room (EmpathyChat *chat)
3847 {
3848         EmpathyChatPriv *priv = GET_PRIV (chat);
3849
3850         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
3851
3852         return (priv->handle_type == TP_HANDLE_TYPE_ROOM);
3853 }
3854
3855 guint
3856 empathy_chat_get_nb_unread_messages (EmpathyChat *self)
3857 {
3858         EmpathyChatPriv *priv = GET_PRIV (self);
3859
3860         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
3861
3862         return priv->unread_messages;
3863 }
3864
3865 /* called when the messages have been read by user */
3866 void
3867 empathy_chat_messages_read (EmpathyChat *self)
3868 {
3869         EmpathyChatPriv *priv = GET_PRIV (self);
3870
3871         g_return_if_fail (EMPATHY_IS_CHAT (self));
3872
3873         /* FIXME: See Bug#610994, See comments about it in EmpathyChatPriv
3874          * definition. If we are still retrieving the backlogs, do not ACK */
3875         if (priv->retrieving_backlogs)
3876                 return;
3877
3878         if (priv->tp_chat != NULL ) {
3879                 empathy_tp_chat_acknowledge_all_messages (priv->tp_chat);
3880         }
3881         priv->unread_messages = 0;
3882
3883         empathy_chat_view_focus_toggled (self->view, TRUE);
3884 }
3885
3886 /* Return TRUE if on of the contacts in this chat is composing */
3887 gboolean
3888 empathy_chat_is_composing (EmpathyChat *chat)
3889 {
3890   return chat->priv->compositors != NULL;
3891 }
3892
3893 gboolean
3894 empathy_chat_is_sms_channel (EmpathyChat *self)
3895 {
3896         EmpathyChatPriv *priv = GET_PRIV (self);
3897
3898         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
3899
3900         return priv->sms_channel;
3901 }
3902
3903 guint
3904 empathy_chat_get_n_messages_sending (EmpathyChat *self)
3905 {
3906         EmpathyChatPriv *priv;
3907
3908         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
3909
3910         priv = GET_PRIV (self);
3911
3912         if (priv->tp_chat == NULL) {
3913                 return 0;
3914         } else {
3915                 guint n_messages;
3916
3917                 g_object_get (priv->tp_chat,
3918                         "n-messages-sending", &n_messages,
3919                         NULL);
3920
3921                 return n_messages;
3922         }
3923 }