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