]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-chat.c
Merge branch 'reference-identities'
[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         EmpathyMessage *message;
872
873         message = empathy_message_new (strv[1]);
874         empathy_message_set_tptype (message, TP_CHANNEL_TEXT_MESSAGE_TYPE_ACTION);
875         empathy_tp_chat_send (priv->tp_chat, message);
876         g_object_unref (message);
877 }
878
879 static void
880 chat_command_say (EmpathyChat *chat,
881                   GStrv        strv)
882 {
883         EmpathyChatPriv *priv = GET_PRIV (chat);
884         EmpathyMessage *message;
885
886         message = empathy_message_new (strv[1]);
887         empathy_tp_chat_send (priv->tp_chat, message);
888         g_object_unref (message);
889 }
890
891 static void chat_command_help (EmpathyChat *chat, GStrv strv);
892
893 typedef void (*ChatCommandFunc) (EmpathyChat *chat, GStrv strv);
894
895 typedef struct {
896         const gchar *prefix;
897         guint min_parts;
898         guint max_parts;
899         ChatCommandFunc func;
900         gboolean (*is_supported)(EmpathyChat *chat);
901         const gchar *help;
902 } ChatCommandItem;
903
904 static ChatCommandItem commands[] = {
905         {"clear", 1, 1, chat_command_clear, NULL,
906          N_("/clear: clear all messages from the current conversation")},
907
908         {"topic", 2, 2, chat_command_topic, NULL,
909          N_("/topic <topic>: set the topic of the current conversation")},
910
911         {"join", 2, 2, chat_command_join, NULL,
912          N_("/join <chat room ID>: join a new chat room")},
913
914         {"j", 2, 2, chat_command_join, NULL,
915          N_("/j <chat room ID>: join a new chat room")},
916
917 #if 0
918         /* FIXME: https://bugzilla.gnome.org/show_bug.cgi?id=643295 */
919         {"part", 1, 3, chat_command_part, part_command_supported,
920          N_("/part [<chat room ID>] [<reason>]: leave the chat room, "
921             "by default the current one")},
922 #endif
923
924         {"query", 2, 3, chat_command_query, NULL,
925          N_("/query <contact ID> [<message>]: open a private chat")},
926
927         {"msg", 3, 3, chat_command_msg, NULL,
928          N_("/msg <contact ID> <message>: open a private chat")},
929
930         {"nick", 2, 2, chat_command_nick, nick_command_supported,
931          N_("/nick <nickname>: change your nickname on the current server")},
932
933         {"me", 2, 2, chat_command_me, NULL,
934          N_("/me <message>: send an ACTION message to the current conversation")},
935
936         {"say", 2, 2, chat_command_say, NULL,
937          N_("/say <message>: send <message> to the current conversation. "
938             "This is used to send a message starting with a '/'. For example: "
939             "\"/say /join is used to join a new chat room\"")},
940
941         {"help", 1, 2, chat_command_help, NULL,
942          N_("/help [<command>]: show all supported commands. "
943             "If <command> is defined, show its usage.")},
944 };
945
946 static void
947 chat_command_show_help (EmpathyChat     *chat,
948                         ChatCommandItem *item)
949 {
950         gchar *str;
951
952         str = g_strdup_printf (_("Usage: %s"), _(item->help));
953         empathy_chat_view_append_event (chat->view, str);
954         g_free (str);
955 }
956
957 static void
958 chat_command_help (EmpathyChat *chat,
959                    GStrv        strv)
960 {
961         guint i;
962
963         /* If <command> part is not defined,
964          * strv[1] will be the terminal NULL */
965         if (strv[1] == NULL) {
966                 for (i = 0; i < G_N_ELEMENTS (commands); i++) {
967                         if (commands[i].is_supported != NULL) {
968                                 if (!commands[i].is_supported (chat)) {
969                                         continue;
970                                 }
971                         }
972                     empathy_chat_view_append_event (chat->view,
973                             _(commands[i].help));
974                 }
975                 return;
976         }
977
978         for (i = 0; i < G_N_ELEMENTS (commands); i++) {
979                 if (g_ascii_strcasecmp (strv[1], commands[i].prefix) == 0) {
980                         if (commands[i].is_supported != NULL) {
981                                 if (!commands[i].is_supported (chat)) {
982                                         break;
983                                 }
984                         }
985                         chat_command_show_help (chat, &commands[i]);
986                         return;
987                 }
988         }
989
990         empathy_chat_view_append_event (chat->view,
991                 _("Unknown command"));
992 }
993
994 static GStrv
995 chat_command_parse (const gchar *text, guint max_parts)
996 {
997         GPtrArray *array;
998         gchar *item;
999
1000         DEBUG ("Parse command, parts=%d text=\"%s\":", max_parts, text);
1001
1002         array = g_ptr_array_sized_new (max_parts + 1);
1003         while (max_parts > 1) {
1004                 const gchar *end;
1005
1006                 /* Skip white spaces */
1007                 while (g_ascii_isspace (*text)) {
1008                         text++;
1009                 }
1010
1011                 /* Search the end of this part, until first space. */
1012                 for (end = text; *end != '\0' && !g_ascii_isspace (*end); end++)
1013                         /* Do nothing */;
1014                 if (*end == '\0') {
1015                         break;
1016                 }
1017
1018                 item = g_strndup (text, end - text);
1019                 g_ptr_array_add (array, item);
1020                 DEBUG ("\tITEM: \"%s\"", item);
1021
1022                 text = end;
1023                 max_parts--;
1024         }
1025
1026         /* Append last part if not empty */
1027         item = g_strstrip (g_strdup (text));
1028         if (!EMP_STR_EMPTY (item)) {
1029                 g_ptr_array_add (array, item);
1030                 DEBUG ("\tITEM: \"%s\"", item);
1031         } else {
1032                 g_free (item);
1033         }
1034
1035         /* Make the array NULL-terminated */
1036         g_ptr_array_add (array, NULL);
1037
1038         return (GStrv) g_ptr_array_free (array, FALSE);
1039 }
1040
1041 static gboolean
1042 has_prefix_case (const gchar *s,
1043                   const gchar *prefix)
1044 {
1045         return g_ascii_strncasecmp (s, prefix, strlen (prefix)) == 0;
1046 }
1047
1048 static void
1049 chat_send (EmpathyChat  *chat,
1050            const gchar *msg)
1051 {
1052         EmpathyChatPriv *priv;
1053         EmpathyMessage  *message;
1054         guint            i;
1055
1056         if (EMP_STR_EMPTY (msg)) {
1057                 return;
1058         }
1059
1060         priv = GET_PRIV (chat);
1061
1062         chat_input_history_add (chat, msg, FALSE);
1063
1064         if (msg[0] == '/') {
1065                 gboolean second_slash = FALSE;
1066                 const gchar *iter = msg + 1;
1067
1068                 for (i = 0; i < G_N_ELEMENTS (commands); i++) {
1069                         GStrv strv;
1070                         guint strv_len;
1071                         gchar c;
1072
1073                         if (!has_prefix_case (msg + 1, commands[i].prefix)) {
1074                                 continue;
1075                         }
1076                         c = *(msg + 1 + strlen (commands[i].prefix));
1077                         if (c != '\0' && !g_ascii_isspace (c)) {
1078                                 continue;
1079                         }
1080                         if (commands[i].is_supported != NULL) {
1081                                 if (!commands[i].is_supported (chat)) {
1082                                         continue;
1083                                 }
1084                         }
1085
1086                         /* We can't use g_strsplit here because it does
1087                          * not deal correctly if we have more than one space
1088                          * between args */
1089                         strv = chat_command_parse (msg + 1, commands[i].max_parts);
1090
1091                         strv_len = g_strv_length (strv);
1092                         if (strv_len < commands[i].min_parts ||
1093                             strv_len > commands[i].max_parts) {
1094                                 chat_command_show_help (chat, &commands[i]);
1095                                 g_strfreev (strv);
1096                                 return;
1097                         }
1098
1099                         commands[i].func (chat, strv);
1100                         g_strfreev (strv);
1101                         return;
1102                 }
1103
1104                 /* Also allow messages with two slashes before the
1105                  * first space, so it is possible to send a /unix/path.
1106                  * This heuristic is kind of crap. */
1107                 while (*iter != '\0' && !g_ascii_isspace (*iter)) {
1108                         if (*iter == '/') {
1109                                 second_slash = TRUE;
1110                                 break;
1111                         }
1112                         iter++;
1113                 }
1114
1115                 if (!second_slash) {
1116                         empathy_chat_view_append_event (chat->view,
1117                                 _("Unknown command; see /help for the available"
1118                                   " commands"));
1119                         return;
1120                 }
1121         }
1122
1123         message = empathy_message_new (msg);
1124         empathy_tp_chat_send (priv->tp_chat, message);
1125         g_object_unref (message);
1126 }
1127
1128 static void
1129 chat_input_text_view_send (EmpathyChat *chat)
1130 {
1131         GtkTextBuffer  *buffer;
1132         GtkTextIter     start, end;
1133         gchar          *msg;
1134
1135         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1136
1137         gtk_text_buffer_get_bounds (buffer, &start, &end);
1138         msg = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1139
1140         /* clear the input field */
1141         gtk_text_buffer_set_text (buffer, "", -1);
1142         /* delete input history modifications */
1143         chat_input_history_revert (chat);
1144
1145         chat_send (chat, msg);
1146         g_free (msg);
1147 }
1148
1149 static void
1150 chat_state_changed_cb (EmpathyTpChat      *tp_chat,
1151                        EmpathyContact     *contact,
1152                        TpChannelChatState  state,
1153                        EmpathyChat        *chat)
1154 {
1155         EmpathyChatPriv *priv;
1156         GList          *l;
1157         gboolean        was_composing;
1158
1159         priv = GET_PRIV (chat);
1160
1161         if (empathy_contact_is_user (contact)) {
1162                 /* We don't care about our own chat state */
1163                 return;
1164         }
1165
1166         was_composing = (priv->compositors != NULL);
1167
1168         /* Find the contact in the list. After that l is the list elem or NULL */
1169         for (l = priv->compositors; l; l = l->next) {
1170                 if (contact == l->data) {
1171                         break;
1172                 }
1173         }
1174
1175         switch (state) {
1176         case TP_CHANNEL_CHAT_STATE_GONE:
1177         case TP_CHANNEL_CHAT_STATE_INACTIVE:
1178         case TP_CHANNEL_CHAT_STATE_PAUSED:
1179         case TP_CHANNEL_CHAT_STATE_ACTIVE:
1180                 /* Contact is not composing */
1181                 if (l) {
1182                         priv->compositors = g_list_remove_link (priv->compositors, l);
1183                         g_object_unref (l->data);
1184                         g_list_free1 (l);
1185                 }
1186                 break;
1187         case TP_CHANNEL_CHAT_STATE_COMPOSING:
1188                 /* Contact is composing */
1189                 if (!l) {
1190                         priv->compositors = g_list_prepend (priv->compositors,
1191                                                             g_object_ref (contact));
1192                 }
1193                 break;
1194         default:
1195                 g_assert_not_reached ();
1196         }
1197
1198         DEBUG ("Was composing: %s now composing: %s",
1199                 was_composing ? "yes" : "no",
1200                 priv->compositors ? "yes" : "no");
1201
1202         if ((was_composing && !priv->compositors) ||
1203             (!was_composing && priv->compositors)) {
1204                 /* Composing state changed */
1205                 g_signal_emit (chat, signals[COMPOSING], 0,
1206                                priv->compositors != NULL);
1207         }
1208 }
1209
1210 static void
1211 chat_message_received (EmpathyChat *chat,
1212         EmpathyMessage *message,
1213         gboolean pending)
1214 {
1215         EmpathyChatPriv *priv = GET_PRIV (chat);
1216         EmpathyContact  *sender;
1217
1218         sender = empathy_message_get_sender (message);
1219
1220         DEBUG ("Appending new message from %s (%d)",
1221                 empathy_contact_get_alias (sender),
1222                 empathy_contact_get_handle (sender));
1223
1224         empathy_chat_view_append_message (chat->view, message);
1225
1226         /* We received a message so the contact is no longer composing */
1227         chat_state_changed_cb (priv->tp_chat, sender,
1228                                TP_CHANNEL_CHAT_STATE_ACTIVE,
1229                                chat);
1230
1231         priv->unread_messages++;
1232         g_signal_emit (chat, signals[NEW_MESSAGE], 0, message, pending);
1233 }
1234
1235 static void
1236 chat_message_received_cb (EmpathyTpChat  *tp_chat,
1237                           EmpathyMessage *message,
1238                           EmpathyChat    *chat)
1239 {
1240         chat_message_received (chat, message, FALSE);
1241 }
1242
1243 static void
1244 chat_send_error_cb (EmpathyTpChat          *tp_chat,
1245                     const gchar            *message_body,
1246                     TpChannelTextSendError  error_code,
1247                     EmpathyChat            *chat)
1248 {
1249         const gchar *error;
1250         gchar       *str;
1251
1252         switch (error_code) {
1253         case TP_CHANNEL_TEXT_SEND_ERROR_OFFLINE:
1254                 error = _("offline");
1255                 break;
1256         case TP_CHANNEL_TEXT_SEND_ERROR_INVALID_CONTACT:
1257                 error = _("invalid contact");
1258                 break;
1259         case TP_CHANNEL_TEXT_SEND_ERROR_PERMISSION_DENIED:
1260                 error = _("permission denied");
1261                 break;
1262         case TP_CHANNEL_TEXT_SEND_ERROR_TOO_LONG:
1263                 error = _("too long message");
1264                 break;
1265         case TP_CHANNEL_TEXT_SEND_ERROR_NOT_IMPLEMENTED:
1266                 error = _("not implemented");
1267                 break;
1268         case TP_CHANNEL_TEXT_SEND_ERROR_UNKNOWN:
1269         default:
1270                 error = _("unknown");
1271                 break;
1272         }
1273
1274         str = g_strdup_printf (_("Error sending message '%s': %s"),
1275                                message_body,
1276                                error);
1277         empathy_chat_view_append_event (chat->view, str);
1278         g_free (str);
1279 }
1280
1281 static void
1282 chat_topic_label_size_allocate_cb (GtkLabel *label,
1283                                    GtkAllocation *allocation,
1284                                    EmpathyChat *chat)
1285 {
1286         EmpathyChatPriv *priv = GET_PRIV (chat);
1287
1288         if (!gtk_label_get_line_wrap (label)) {
1289                 if (pango_layout_is_ellipsized (gtk_label_get_layout (label)))
1290                         gtk_widget_show (priv->expander_topic);
1291                 else
1292                         gtk_widget_hide (priv->expander_topic);
1293
1294                 return;
1295         }
1296 }
1297
1298 static void
1299 chat_topic_expander_activate_cb (GtkExpander *expander,
1300                                  GParamSpec *param_spec,
1301                                  EmpathyChat *chat)
1302 {
1303         EmpathyChatPriv *priv = GET_PRIV (chat);
1304
1305         if (gtk_expander_get_expanded (expander)) {
1306                 gtk_label_set_ellipsize (GTK_LABEL (priv->label_topic), PANGO_ELLIPSIZE_NONE);
1307                 gtk_label_set_line_wrap (GTK_LABEL (priv->label_topic), TRUE);
1308         } else {
1309                 gtk_label_set_ellipsize (GTK_LABEL (priv->label_topic), PANGO_ELLIPSIZE_END);
1310                 gtk_label_set_line_wrap (GTK_LABEL (priv->label_topic), FALSE);
1311         }
1312 }
1313
1314 static void
1315 chat_property_changed_cb (EmpathyTpChat *tp_chat,
1316                           const gchar   *name,
1317                           GValue        *value,
1318                           EmpathyChat   *chat)
1319 {
1320         EmpathyChatPriv *priv = GET_PRIV (chat);
1321
1322         if (!tp_strdiff (name, "subject")) {
1323                 g_free (priv->subject);
1324                 priv->subject = g_value_dup_string (value);
1325                 g_object_notify (G_OBJECT (chat), "subject");
1326
1327                 if (EMP_STR_EMPTY (priv->subject)) {
1328                         gtk_widget_hide (priv->hbox_topic);
1329                 } else {
1330                         gchar *markup_topic;
1331                         gchar *markup_text;
1332
1333                         markup_topic = empathy_add_link_markup (priv->subject);
1334                         markup_text = g_strdup_printf ("<span weight=\"bold\">%s</span> %s",
1335                                 _("Topic:"), markup_topic);
1336
1337                         gtk_label_set_markup (GTK_LABEL (priv->label_topic), markup_text);
1338                         g_free (markup_text);
1339                         g_free (markup_topic);
1340
1341                         gtk_widget_show (priv->hbox_topic);
1342                 }
1343                 if (priv->block_events_timeout_id == 0) {
1344                         gchar *str;
1345
1346                         if (!EMP_STR_EMPTY (priv->subject)) {
1347                                 str = g_strdup_printf (_("Topic set to: %s"), priv->subject);
1348                         } else {
1349                                 str = g_strdup (_("No topic defined"));
1350                         }
1351                         empathy_chat_view_append_event (EMPATHY_CHAT (chat)->view, str);
1352                         g_free (str);
1353                 }
1354         }
1355         else if (!tp_strdiff (name, "name")) {
1356                 g_free (priv->name);
1357                 priv->name = g_value_dup_string (value);
1358                 g_object_notify (G_OBJECT (chat), "name");
1359         }
1360 }
1361
1362 static gboolean
1363 chat_input_text_get_word_from_iter (GtkTextIter   *iter,
1364                                     GtkTextIter   *start,
1365                                     GtkTextIter   *end)
1366 {
1367         GtkTextIter word_start = *iter;
1368         GtkTextIter word_end = *iter;
1369         GtkTextIter tmp;
1370
1371         if (gtk_text_iter_inside_word (&word_end) &&
1372                         !gtk_text_iter_ends_word (&word_end)) {
1373                 gtk_text_iter_forward_word_end (&word_end);
1374         }
1375
1376         tmp = word_end;
1377
1378         if (gtk_text_iter_get_char (&tmp) == '\'') {
1379                 gtk_text_iter_forward_char (&tmp);
1380
1381                 if (g_unichar_isalpha (gtk_text_iter_get_char (&tmp))) {
1382                         gtk_text_iter_forward_word_end (&word_end);
1383                 }
1384         }
1385
1386
1387         if (gtk_text_iter_inside_word (&word_start) ||
1388                         gtk_text_iter_ends_word (&word_start)) {
1389                 if (!gtk_text_iter_starts_word (&word_start) ||
1390                                 gtk_text_iter_equal (&word_start, &word_end)) {
1391                         gtk_text_iter_backward_word_start (&word_start);
1392                 }
1393
1394                 tmp = word_start;
1395                 gtk_text_iter_backward_char (&tmp);
1396
1397                 if (gtk_text_iter_get_char (&tmp) == '\'') {
1398                         gtk_text_iter_backward_char (&tmp);
1399
1400                         if (g_unichar_isalpha (gtk_text_iter_get_char (&tmp))) {
1401                                 gtk_text_iter_backward_word_start (&word_start);
1402                         }
1403                 }
1404         }
1405
1406         *start = word_start;
1407         *end = word_end;
1408         return TRUE;
1409 }
1410
1411 static void
1412 chat_input_text_buffer_insert_text_cb (GtkTextBuffer *buffer,
1413                                        GtkTextIter   *location,
1414                                        gchar         *text,
1415                                        gint           len,
1416                                        EmpathyChat   *chat)
1417 {
1418         GtkTextIter iter, pos;
1419
1420         /* Remove all misspelled tags in the inserted text.
1421          * This happens when text is inserted within a misspelled word. */
1422         gtk_text_buffer_get_iter_at_offset (buffer, &iter,
1423                                             gtk_text_iter_get_offset (location) - len);
1424         gtk_text_buffer_remove_tag_by_name (buffer, "misspelled",
1425                                             &iter, location);
1426
1427         gtk_text_buffer_get_iter_at_mark (buffer, &pos, gtk_text_buffer_get_insert (buffer));
1428
1429         do {
1430                 GtkTextIter start, end;
1431                 gchar *str;
1432
1433                 if (!chat_input_text_get_word_from_iter (&iter, &start, &end))
1434                         continue;
1435
1436                 str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1437
1438                 if (gtk_text_iter_in_range (&pos, &start, &end) ||
1439                                 gtk_text_iter_equal (&pos, &end) ||
1440                                 empathy_spell_check (str)) {
1441                         gtk_text_buffer_remove_tag_by_name (buffer, "misspelled", &start, &end);
1442                 } else {
1443                         gtk_text_buffer_apply_tag_by_name (buffer, "misspelled", &start, &end);
1444                 }
1445
1446                 g_free (str);
1447
1448         } while (gtk_text_iter_forward_word_end (&iter) &&
1449                  gtk_text_iter_compare (&iter, location) <= 0);
1450 }
1451
1452 static void
1453 chat_input_text_buffer_delete_range_cb (GtkTextBuffer *buffer,
1454                                         GtkTextIter   *start,
1455                                         GtkTextIter   *end,
1456                                         EmpathyChat   *chat)
1457 {
1458         GtkTextIter word_start, word_end;
1459
1460         if (chat_input_text_get_word_from_iter (start, &word_start, &word_end)) {
1461                 gtk_text_buffer_remove_tag_by_name (buffer, "misspelled",
1462                                                     &word_start, &word_end);
1463         }
1464 }
1465
1466 static void
1467 chat_input_text_buffer_changed_cb (GtkTextBuffer *buffer,
1468                                    EmpathyChat    *chat)
1469 {
1470         if (gtk_text_buffer_get_char_count (buffer) == 0) {
1471                 chat_composing_stop (chat);
1472         } else {
1473                 chat_composing_start (chat);
1474         }
1475 }
1476
1477 static void
1478 chat_input_text_buffer_notify_cursor_position_cb (GtkTextBuffer *buffer,
1479                                                   GParamSpec    *pspec,
1480                                                   EmpathyChat    *chat)
1481 {
1482         GtkTextIter pos;
1483         GtkTextIter prev_pos;
1484         GtkTextIter word_start;
1485         GtkTextIter word_end;
1486         GtkTextMark *mark;
1487         gchar *str;
1488
1489         mark = gtk_text_buffer_get_mark (buffer, "previous-cursor-position");
1490
1491         gtk_text_buffer_get_iter_at_mark (buffer, &pos,
1492                                           gtk_text_buffer_get_insert (buffer));
1493         gtk_text_buffer_get_iter_at_mark (buffer, &prev_pos, mark);
1494
1495         if (!chat_input_text_get_word_from_iter (&prev_pos, &word_start, &word_end))
1496                 goto out;
1497
1498         if (!gtk_text_iter_in_range (&pos, &word_start, &word_end) &&
1499                         !gtk_text_iter_equal (&pos, &word_end)) {
1500                 str = gtk_text_buffer_get_text (buffer,
1501                                         &word_start, &word_end, FALSE);
1502
1503                 if (!empathy_spell_check (str)) {
1504                         gtk_text_buffer_apply_tag_by_name (buffer,
1505                                         "misspelled", &word_start, &word_end);
1506                 } else {
1507                         gtk_text_buffer_remove_tag_by_name (buffer,
1508                                         "misspelled", &word_start, &word_end);
1509                 }
1510
1511                 g_free (str);
1512         }
1513
1514 out:
1515         gtk_text_buffer_move_mark (buffer, mark, &pos);
1516 }
1517
1518 static gboolean
1519 empathy_isspace_cb (gunichar c,
1520                  gpointer data)
1521 {
1522         return g_unichar_isspace (c);
1523 }
1524
1525 static gboolean
1526 chat_input_key_press_event_cb (GtkWidget   *widget,
1527                                GdkEventKey *event,
1528                                EmpathyChat *chat)
1529 {
1530         EmpathyChatPriv *priv;
1531         GtkAdjustment  *adj;
1532         gdouble         val;
1533         GtkWidget      *text_view_sw;
1534
1535         priv = GET_PRIV (chat);
1536
1537         /* Catch ctrl+up/down so we can traverse messages we sent */
1538         if ((event->state & GDK_CONTROL_MASK) &&
1539             (event->keyval == GDK_KEY_Up ||
1540              event->keyval == GDK_KEY_Down)) {
1541                 GtkTextBuffer *buffer;
1542                 const gchar   *str;
1543
1544                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1545                 chat_input_history_update (chat, buffer);
1546
1547                 if (event->keyval == GDK_KEY_Up) {
1548                         str = chat_input_history_get_next (chat);
1549                 } else {
1550                         str = chat_input_history_get_prev (chat);
1551                 }
1552
1553                 g_signal_handlers_block_by_func (buffer,
1554                                                  chat_input_text_buffer_changed_cb,
1555                                                  chat);
1556                 gtk_text_buffer_set_text (buffer, str ? str : "", -1);
1557                 g_signal_handlers_unblock_by_func (buffer,
1558                                                    chat_input_text_buffer_changed_cb,
1559                                                    chat);
1560
1561                 return TRUE;
1562         }
1563
1564         /* Catch enter but not ctrl/shift-enter */
1565         if (IS_ENTER (event->keyval) &&
1566             !(event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
1567                 GtkTextView *view;
1568
1569                 /* This is to make sure that kinput2 gets the enter. And if
1570                  * it's handled there we shouldn't send on it. This is because
1571                  * kinput2 uses Enter to commit letters. See:
1572                  * http://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=104299
1573                  */
1574
1575                 view = GTK_TEXT_VIEW (chat->input_text_view);
1576                 if (gtk_text_view_im_context_filter_keypress (view, event)) {
1577                         gtk_text_view_reset_im_context (view);
1578                         return TRUE;
1579                 }
1580
1581                 chat_input_text_view_send (chat);
1582                 return TRUE;
1583         }
1584
1585         text_view_sw = gtk_widget_get_parent (GTK_WIDGET (chat->view));
1586
1587         if (IS_ENTER (event->keyval) &&
1588             (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
1589                 /* Newline for shift/control-enter. */
1590                 return FALSE;
1591         }
1592         if (!(event->state & GDK_CONTROL_MASK) &&
1593             event->keyval == GDK_KEY_Page_Up) {
1594                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
1595                 gtk_adjustment_set_value (adj, gtk_adjustment_get_value (adj) - gtk_adjustment_get_page_size (adj));
1596                 return TRUE;
1597         }
1598         if ((event->state & GDK_CONTROL_MASK) != GDK_CONTROL_MASK &&
1599             event->keyval == GDK_KEY_Page_Down) {
1600                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
1601                 val = MIN (gtk_adjustment_get_value (adj) + gtk_adjustment_get_page_size (adj),
1602                            gtk_adjustment_get_upper (adj) - gtk_adjustment_get_page_size (adj));
1603                 gtk_adjustment_set_value (adj, val);
1604                 return TRUE;
1605         }
1606         if (event->keyval == GDK_KEY_Escape) {
1607                 empathy_search_bar_hide (EMPATHY_SEARCH_BAR (priv->search_bar));
1608         }
1609         if (!(event->state & (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) &&
1610             event->keyval == GDK_KEY_Tab) {
1611                 GtkTextBuffer *buffer;
1612                 GtkTextIter    start, current;
1613                 gchar         *nick, *completed;
1614                 GList         *list, *completed_list;
1615                 gboolean       is_start_of_buffer;
1616
1617                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (EMPATHY_CHAT (chat)->input_text_view));
1618                 gtk_text_buffer_get_iter_at_mark (buffer, &current, gtk_text_buffer_get_insert (buffer));
1619
1620                 /* Get the start of the nick to complete. */
1621                 gtk_text_buffer_get_iter_at_mark (buffer, &start, gtk_text_buffer_get_insert (buffer));
1622                 if (gtk_text_iter_backward_find_char (&start, &empathy_isspace_cb, NULL, NULL)) {
1623                         gtk_text_iter_set_offset (&start, gtk_text_iter_get_offset (&start) + 1);
1624                 }
1625                 is_start_of_buffer = gtk_text_iter_is_start (&start);
1626
1627                 list = empathy_contact_list_get_members (EMPATHY_CONTACT_LIST (priv->tp_chat));
1628                 g_completion_add_items (priv->completion, list);
1629
1630                 nick = gtk_text_buffer_get_text (buffer, &start, &current, FALSE);
1631                 completed_list = g_completion_complete (priv->completion,
1632                                                         nick,
1633                                                         &completed);
1634
1635                 g_free (nick);
1636
1637                 if (completed) {
1638                         guint        len;
1639                         const gchar *text;
1640                         GString     *message = NULL;
1641                         GList       *l;
1642
1643                         gtk_text_buffer_delete (buffer, &start, &current);
1644
1645                         len = g_list_length (completed_list);
1646
1647                         if (len == 1) {
1648                                 /* If we only have one hit, use that text
1649                                  * instead of the text in completed since the
1650                                  * completed text will use the typed string
1651                                  * which might be cased all wrong.
1652                                  * Fixes #120876
1653                                  * */
1654                                 text = empathy_contact_get_alias (completed_list->data);
1655                         } else {
1656                                 text = completed;
1657
1658                                 /* Print all hits to the scrollback view, so the
1659                                  * user knows what possibilities he has.
1660                                  * Fixes #599779
1661                                  * */
1662                                  message = g_string_new ("");
1663                                  for (l = completed_list; l != NULL; l = l->next) {
1664                                         g_string_append (message, empathy_contact_get_alias (l->data));
1665                                         g_string_append (message, " - ");
1666                                  }
1667                                  empathy_chat_view_append_event (chat->view, message->str);
1668                                  g_string_free (message, TRUE);
1669                         }
1670
1671                         gtk_text_buffer_insert_at_cursor (buffer, text, strlen (text));
1672
1673                         if (len == 1 && is_start_of_buffer) {
1674                             gchar *complete_char;
1675
1676                             complete_char = g_settings_get_string (
1677                                     priv->gsettings_chat,
1678                                     EMPATHY_PREFS_CHAT_NICK_COMPLETION_CHAR);
1679
1680                             if (complete_char != NULL) {
1681                                 gtk_text_buffer_insert_at_cursor (buffer,
1682                                                                   complete_char,
1683                                                                   strlen (complete_char));
1684                                 gtk_text_buffer_insert_at_cursor (buffer, " ", 1);
1685                                 g_free (complete_char);
1686                             }
1687                         }
1688
1689                         g_free (completed);
1690                 }
1691
1692                 g_completion_clear_items (priv->completion);
1693
1694                 g_list_foreach (list, (GFunc) g_object_unref, NULL);
1695                 g_list_free (list);
1696
1697                 return TRUE;
1698         }
1699
1700         return FALSE;
1701 }
1702
1703 static gboolean
1704 chat_text_view_focus_in_event_cb (GtkWidget  *widget,
1705                                   GdkEvent   *event,
1706                                   EmpathyChat *chat)
1707 {
1708         gtk_widget_grab_focus (chat->input_text_view);
1709
1710         return TRUE;
1711 }
1712
1713 static void
1714 chat_input_realize_cb (GtkWidget   *widget,
1715                        EmpathyChat *chat)
1716 {
1717         DEBUG ("Setting focus to the input text view");
1718         if (gtk_widget_is_sensitive (widget)) {
1719                 gtk_widget_grab_focus (widget);
1720         }
1721 }
1722
1723 static void
1724 chat_insert_smiley_activate_cb (EmpathySmileyManager *manager,
1725                                 EmpathySmiley        *smiley,
1726                                 gpointer              user_data)
1727 {
1728         EmpathyChat   *chat = EMPATHY_CHAT (user_data);
1729         GtkTextBuffer *buffer;
1730         GtkTextIter    iter;
1731
1732         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1733
1734         gtk_text_buffer_get_end_iter (buffer, &iter);
1735         gtk_text_buffer_insert (buffer, &iter, smiley->str, -1);
1736
1737         gtk_text_buffer_get_end_iter (buffer, &iter);
1738         gtk_text_buffer_insert (buffer, &iter, " ", -1);
1739 }
1740
1741 typedef struct {
1742         EmpathyChat  *chat;
1743         gchar       *word;
1744
1745         GtkTextIter  start;
1746         GtkTextIter  end;
1747 } EmpathyChatSpell;
1748
1749 static EmpathyChatSpell *
1750 chat_spell_new (EmpathyChat  *chat,
1751                 const gchar *word,
1752                 GtkTextIter  start,
1753                 GtkTextIter  end)
1754 {
1755         EmpathyChatSpell *chat_spell;
1756
1757         chat_spell = g_slice_new0 (EmpathyChatSpell);
1758
1759         chat_spell->chat = g_object_ref (chat);
1760         chat_spell->word = g_strdup (word);
1761         chat_spell->start = start;
1762         chat_spell->end = end;
1763
1764         return chat_spell;
1765 }
1766
1767 static void
1768 chat_spell_free (EmpathyChatSpell *chat_spell)
1769 {
1770         g_object_unref (chat_spell->chat);
1771         g_free (chat_spell->word);
1772         g_slice_free (EmpathyChatSpell, chat_spell);
1773 }
1774
1775 static void
1776 chat_spelling_menu_activate_cb (GtkMenuItem     *menu_item,
1777                                                 EmpathyChatSpell *chat_spell)
1778 {
1779     empathy_chat_correct_word (chat_spell->chat,
1780                                &(chat_spell->start),
1781                                &(chat_spell->end),
1782                                gtk_menu_item_get_label (menu_item));
1783 }
1784
1785
1786 static GtkWidget *
1787 chat_spelling_build_suggestions_menu (const gchar *code,
1788                                       EmpathyChatSpell *chat_spell)
1789 {
1790         GList     *suggestions, *l;
1791         GtkWidget *menu, *menu_item;
1792
1793         suggestions = empathy_spell_get_suggestions (code, chat_spell->word);
1794         if (suggestions == NULL)
1795                 return NULL;
1796
1797         menu = gtk_menu_new ();
1798         for (l = suggestions; l; l = l->next) {
1799                 menu_item = gtk_menu_item_new_with_label (l->data);
1800                 g_signal_connect (G_OBJECT (menu_item), "activate",
1801                                   G_CALLBACK (chat_spelling_menu_activate_cb),
1802                                   chat_spell);
1803                 gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
1804         }
1805         empathy_spell_free_suggestions (suggestions);
1806
1807         gtk_widget_show_all (menu);
1808
1809         return menu;
1810 }
1811
1812 static GtkWidget *
1813 chat_spelling_build_menu (EmpathyChatSpell *chat_spell)
1814 {
1815         GtkWidget *menu, *submenu, *item;
1816         GList     *codes, *l;
1817
1818         codes = empathy_spell_get_enabled_language_codes ();
1819         g_assert (codes != NULL);
1820
1821         if (g_list_length (codes) > 1) {
1822                 menu = gtk_menu_new ();
1823
1824                 for (l = codes; l; l = l->next) {
1825                         const gchar *code, *name;
1826
1827                         code = l->data;
1828                         name = empathy_spell_get_language_name (code);
1829                         if (!name)
1830                                 continue;
1831
1832                         item = gtk_image_menu_item_new_with_label (name);
1833
1834                         submenu = chat_spelling_build_suggestions_menu (
1835                                         code, chat_spell);
1836                         if (submenu == NULL)
1837                                 gtk_widget_set_sensitive (item, FALSE);
1838                         else
1839                                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item),
1840                                                            submenu);
1841                         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1842                 }
1843         } else {
1844                 menu = chat_spelling_build_suggestions_menu (codes->data,
1845                                                              chat_spell);
1846                 if (menu == NULL) {
1847                         menu = gtk_menu_new ();
1848                         item = gtk_menu_item_new_with_label (_("(No Suggestions)"));
1849                         gtk_widget_set_sensitive (item, FALSE);
1850                         gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
1851                 }
1852         }
1853         g_list_free (codes);
1854
1855         gtk_widget_show_all (menu);
1856
1857         return menu;
1858 }
1859
1860 typedef struct {
1861         EmpathyChat  *chat;
1862         gchar        *word;
1863         gchar        *code;
1864 } EmpathyChatWord;
1865
1866 static EmpathyChatWord *
1867 chat_word_new (EmpathyChat  *chat,
1868                 const gchar  *word,
1869                 const gchar  *code)
1870 {
1871         EmpathyChatWord *chat_word;
1872
1873         chat_word = g_slice_new0 (EmpathyChatWord);
1874
1875         chat_word->chat = g_object_ref (chat);
1876         chat_word->word = g_strdup (word);
1877         chat_word->code = g_strdup (code);
1878
1879         return chat_word;
1880 }
1881
1882 static void
1883 chat_word_free (EmpathyChatWord *chat_word)
1884 {
1885         g_object_unref (chat_word->chat);
1886         g_free (chat_word->word);
1887         g_free (chat_word->code);
1888         g_slice_free (EmpathyChatWord, chat_word);
1889 }
1890
1891 static void
1892 chat_add_to_dictionary_activate_cb (GtkMenuItem     *menu_item,
1893                                     EmpathyChatWord *chat_word)
1894 {
1895         EmpathyChatPriv *priv = GET_PRIV (chat_word->chat);
1896
1897         empathy_spell_add_to_dictionary (chat_word->code,
1898                                          chat_word->word);
1899         priv->update_misspelled_words_id =
1900                 g_idle_add (update_misspelled_words, chat_word->chat);
1901 }
1902
1903 static GtkWidget *
1904 chat_spelling_build_add_to_dictionary_item (EmpathyChatSpell *chat_spell)
1905 {
1906         GtkWidget       *menu, *item, *lang_item, *image;
1907         GList           *codes, *l;
1908         gchar           *label;
1909         const gchar     *code, *name;
1910         EmpathyChatWord *chat_word;
1911
1912         codes = empathy_spell_get_enabled_language_codes ();
1913         g_assert (codes != NULL);
1914         if (g_list_length (codes) > 1) {
1915                 /* translators: %s is the selected word */
1916                 label = g_strdup_printf (_("Add '%s' to Dictionary"),
1917                                         chat_spell->word);
1918                 item = gtk_image_menu_item_new_with_mnemonic (label);
1919                 g_free (label);
1920                 image = gtk_image_new_from_icon_name (GTK_STOCK_ADD,
1921                                                       GTK_ICON_SIZE_MENU);
1922                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item),
1923                                                image);
1924
1925                 menu = gtk_menu_new ();
1926
1927                 for (l = codes; l; l = l->next) {
1928                         code = l->data;
1929                         name = empathy_spell_get_language_name (code);
1930                         if (name == NULL)
1931                                 continue;
1932
1933                         lang_item = gtk_image_menu_item_new_with_label (name);
1934
1935                         chat_word= chat_word_new (chat_spell->chat,
1936                                                   chat_spell->word, code);
1937                         g_object_set_data_full (G_OBJECT (lang_item),
1938                                 "chat-word", chat_word,
1939                                 (GDestroyNotify) chat_word_free);
1940
1941                         g_signal_connect (G_OBJECT (lang_item), "activate",
1942                                 G_CALLBACK (chat_add_to_dictionary_activate_cb),
1943                                 chat_word);
1944                         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), lang_item);
1945                 }
1946                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), menu);
1947         } else {
1948                 code = codes->data;
1949                 name = empathy_spell_get_language_name (code);
1950                 g_assert (name != NULL);
1951                 /* translators: first %s is the selected word,
1952                  * second %s is the language name of the target dictionary */
1953                 label = g_strdup_printf (_("Add '%s' to %s Dictionary"),
1954                                         chat_spell->word, name);
1955                 item = gtk_image_menu_item_new_with_mnemonic (label);
1956                 g_free (label);
1957                 image = gtk_image_new_from_icon_name (GTK_STOCK_ADD,
1958                                                       GTK_ICON_SIZE_MENU);
1959                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
1960
1961                 chat_word = chat_word_new (chat_spell->chat, chat_spell->word,
1962                                            code);
1963                 g_object_set_data_full (G_OBJECT (item), "chat-word", chat_word,
1964                                         (GDestroyNotify) chat_word_free);
1965
1966                 g_signal_connect (G_OBJECT (item), "activate",
1967                                   G_CALLBACK (chat_add_to_dictionary_activate_cb),
1968                                   chat_word);
1969         }
1970         g_list_free (codes);
1971
1972         gtk_widget_show_all (item);
1973
1974         return item;
1975 }
1976
1977 static void
1978 chat_text_send_cb (GtkMenuItem *menuitem,
1979                    EmpathyChat *chat)
1980 {
1981         chat_input_text_view_send (chat);
1982 }
1983
1984 static void
1985 chat_input_populate_popup_cb (GtkTextView *view,
1986                               GtkMenu     *menu,
1987                               EmpathyChat *chat)
1988 {
1989         GtkTextBuffer        *buffer;
1990         GtkTextTagTable      *table;
1991         GtkTextTag           *tag;
1992         gint                  x, y;
1993         GtkTextIter           iter, start, end;
1994         GtkWidget            *item;
1995         gchar                *str = NULL;
1996         EmpathyChatSpell     *chat_spell;
1997         GtkWidget            *spell_menu;
1998         GtkWidget            *spell_item;
1999         EmpathySmileyManager *smiley_manager;
2000         GtkWidget            *smiley_menu;
2001         GtkWidget            *image;
2002
2003         buffer = gtk_text_view_get_buffer (view);
2004
2005         /* Add the emoticon menu. */
2006         item = gtk_separator_menu_item_new ();
2007         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2008         gtk_widget_show (item);
2009
2010         item = gtk_image_menu_item_new_with_mnemonic (_("Insert Smiley"));
2011         image = gtk_image_new_from_icon_name ("face-smile",
2012                                               GTK_ICON_SIZE_MENU);
2013         gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
2014         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2015         gtk_widget_show (item);
2016
2017         smiley_manager = empathy_smiley_manager_dup_singleton ();
2018         smiley_menu = empathy_smiley_menu_new (smiley_manager,
2019                                                chat_insert_smiley_activate_cb,
2020                                                chat);
2021         gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), smiley_menu);
2022         g_object_unref (smiley_manager);
2023
2024         /* Add the Send menu item. */
2025         gtk_text_buffer_get_bounds (buffer, &start, &end);
2026         str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
2027         if (!EMP_STR_EMPTY (str)) {
2028                 item = gtk_menu_item_new_with_mnemonic (_("_Send"));
2029                 g_signal_connect (G_OBJECT (item), "activate",
2030                                   G_CALLBACK (chat_text_send_cb), chat);
2031                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2032                 gtk_widget_show (item);
2033         }
2034         str = NULL;
2035
2036         /* Add the spell check menu item. */
2037         table = gtk_text_buffer_get_tag_table (buffer);
2038         tag = gtk_text_tag_table_lookup (table, "misspelled");
2039         gtk_widget_get_pointer (GTK_WIDGET (view), &x, &y);
2040         gtk_text_view_window_to_buffer_coords (GTK_TEXT_VIEW (view),
2041                                                GTK_TEXT_WINDOW_WIDGET,
2042                                                x, y,
2043                                                &x, &y);
2044         gtk_text_view_get_iter_at_location (GTK_TEXT_VIEW (view), &iter, x, y);
2045         start = end = iter;
2046         if (gtk_text_iter_backward_to_tag_toggle (&start, tag) &&
2047             gtk_text_iter_forward_to_tag_toggle (&end, tag)) {
2048
2049                 str = gtk_text_buffer_get_text (buffer,
2050                                                 &start, &end, FALSE);
2051         }
2052         if (!EMP_STR_EMPTY (str)) {
2053                 chat_spell = chat_spell_new (chat, str, start, end);
2054                 g_object_set_data_full (G_OBJECT (menu),
2055                                         "chat-spell", chat_spell,
2056                                         (GDestroyNotify) chat_spell_free);
2057
2058                 item = gtk_separator_menu_item_new ();
2059                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2060                 gtk_widget_show (item);
2061
2062                 /* Spelling suggestions */
2063                 item = gtk_image_menu_item_new_with_mnemonic (_("_Spelling Suggestions"));
2064                 image = gtk_image_new_from_icon_name (GTK_STOCK_SPELL_CHECK,
2065                                                       GTK_ICON_SIZE_MENU);
2066                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
2067
2068                 spell_menu = chat_spelling_build_menu (chat_spell);
2069                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), spell_menu);
2070
2071
2072                 spell_item = gtk_separator_menu_item_new ();
2073                 gtk_menu_shell_append (GTK_MENU_SHELL (spell_menu), spell_item);
2074                 gtk_widget_show (spell_item);
2075
2076                 /* Add to dictionary */
2077                 spell_item = chat_spelling_build_add_to_dictionary_item (chat_spell);
2078
2079                 gtk_menu_shell_append (GTK_MENU_SHELL (spell_menu), spell_item);
2080                 gtk_widget_show (spell_item);
2081
2082                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2083                 gtk_widget_show (item);
2084         }
2085 }
2086
2087
2088 static gboolean
2089 chat_log_filter (TplEvent *log,
2090                  gpointer user_data)
2091 {
2092         EmpathyChat *chat = user_data;
2093         EmpathyMessage *message;
2094         EmpathyChatPriv *priv = GET_PRIV (chat);
2095         const GList *pending;
2096
2097         g_return_val_if_fail (TPL_IS_EVENT (log), FALSE);
2098         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
2099
2100         pending = empathy_tp_chat_get_pending_messages (priv->tp_chat);
2101         message = empathy_message_from_tpl_log_event (log);
2102
2103         for (; pending; pending = g_list_next (pending)) {
2104                 if (empathy_message_equal (message, pending->data)) {
2105                         g_object_unref (message);
2106                         return FALSE;
2107                 }
2108         }
2109
2110         g_object_unref (message);
2111         return TRUE;
2112 }
2113
2114
2115 static void
2116 show_pending_messages (EmpathyChat *chat) {
2117         EmpathyChatPriv *priv = GET_PRIV (chat);
2118         const GList *messages, *l;
2119
2120         g_return_if_fail (EMPATHY_IS_CHAT (chat));
2121
2122         if (chat->view == NULL || priv->tp_chat == NULL)
2123                 return;
2124
2125         if (!priv->can_show_pending)
2126                 return;
2127
2128         messages = empathy_tp_chat_get_pending_messages (priv->tp_chat);
2129
2130         for (l = messages; l != NULL ; l = g_list_next (l)) {
2131                 EmpathyMessage *message = EMPATHY_MESSAGE (l->data);
2132                 chat_message_received (chat, message, TRUE);
2133         }
2134 }
2135
2136
2137 static void
2138 got_filtered_messages_cb (GObject *manager,
2139                 GAsyncResult *result,
2140                 gpointer user_data)
2141 {
2142         GList *l;
2143         GList *messages;
2144         EmpathyChat *chat = EMPATHY_CHAT (user_data);
2145         EmpathyChatPriv *priv = GET_PRIV (chat);
2146         GError *error = NULL;
2147
2148         if (!tpl_log_manager_get_filtered_events_finish (TPL_LOG_MANAGER (manager),
2149                 result, &messages, &error)) {
2150                 DEBUG ("%s. Aborting.", error->message);
2151                 empathy_chat_view_append_event (chat->view,
2152                         _("Failed to retrieve recent logs"));
2153                 g_error_free (error);
2154                 goto out;
2155         }
2156
2157         for (l = messages; l; l = g_list_next (l)) {
2158                 EmpathyMessage *message;
2159                 g_assert (TPL_IS_EVENT (l->data));
2160
2161                 message = empathy_message_from_tpl_log_event (l->data);
2162                 g_object_unref (l->data);
2163
2164                 empathy_chat_view_append_message (chat->view, message);
2165                 g_object_unref (message);
2166         }
2167         g_list_free (messages);
2168
2169 out:
2170         /* in case of TPL error, skip backlog and show pending messages */
2171         priv->can_show_pending = TRUE;
2172         show_pending_messages (chat);
2173
2174         /* FIXME: See Bug#610994, we are forcing the ACK of the queue. See comments
2175          * about it in EmpathyChatPriv definition */
2176         priv->retrieving_backlogs = FALSE;
2177         empathy_chat_messages_read (chat);
2178
2179         /* Turn back on scrolling */
2180         empathy_chat_view_scroll (chat->view, TRUE);
2181 }
2182
2183 static void
2184 chat_add_logs (EmpathyChat *chat)
2185 {
2186         EmpathyChatPriv *priv = GET_PRIV (chat);
2187         TplEntity       *target;
2188
2189         if (!priv->id) {
2190                 return;
2191         }
2192
2193         /* Turn off scrolling temporarily */
2194         empathy_chat_view_scroll (chat->view, FALSE);
2195
2196         /* Add messages from last conversation */
2197         if (priv->handle_type == TP_HANDLE_TYPE_ROOM)
2198           target = tpl_entity_new_from_room_id (priv->id);
2199         else
2200           target = tpl_entity_new (priv->id, TPL_ENTITY_CONTACT, NULL, NULL);
2201
2202         priv->retrieving_backlogs = TRUE;
2203         tpl_log_manager_get_filtered_events_async (priv->log_manager,
2204                                                    priv->account,
2205                                                    target,
2206                                                    TPL_EVENT_MASK_TEXT,
2207                                                    5,
2208                                                    chat_log_filter,
2209                                                    chat,
2210                                                    got_filtered_messages_cb,
2211                                                    (gpointer) chat);
2212
2213         g_object_unref (target);
2214 }
2215
2216 static gint
2217 chat_contacts_completion_func (const gchar *s1,
2218                                const gchar *s2,
2219                                gsize        n)
2220 {
2221         gchar *tmp, *nick1, *nick2;
2222         gint   ret;
2223
2224         if (s1 == s2) {
2225                 return 0;
2226         }
2227         if (!s1 || !s2) {
2228                 return s1 ? -1 : +1;
2229         }
2230
2231         tmp = g_utf8_normalize (s1, -1, G_NORMALIZE_DEFAULT);
2232         nick1 = g_utf8_casefold (tmp, -1);
2233         g_free (tmp);
2234
2235         tmp = g_utf8_normalize (s2, -1, G_NORMALIZE_DEFAULT);
2236         nick2 = g_utf8_casefold (tmp, -1);
2237         g_free (tmp);
2238
2239         ret = strncmp (nick1, nick2, n);
2240
2241         g_free (nick1);
2242         g_free (nick2);
2243
2244         return ret;
2245 }
2246
2247 static gchar *
2248 build_part_message (guint           reason,
2249                     const gchar    *name,
2250                     EmpathyContact *actor,
2251                     const gchar    *message)
2252 {
2253         GString *s = g_string_new ("");
2254         const gchar *actor_name = NULL;
2255
2256         if (actor != NULL) {
2257                 actor_name = empathy_contact_get_alias (actor);
2258         }
2259
2260         /* Having an actor only really makes sense for a few actions... */
2261         switch (reason) {
2262         case TP_CHANNEL_GROUP_CHANGE_REASON_OFFLINE:
2263                 g_string_append_printf (s, _("%s has disconnected"), name);
2264                 break;
2265         case TP_CHANNEL_GROUP_CHANGE_REASON_KICKED:
2266                 if (actor_name != NULL) {
2267                         /* translators: reverse the order of these arguments
2268                          * if the kicked should come before the kicker in your locale.
2269                          */
2270                         g_string_append_printf (s, _("%1$s was kicked by %2$s"),
2271                                 name, actor_name);
2272                 } else {
2273                         g_string_append_printf (s, _("%s was kicked"), name);
2274                 }
2275                 break;
2276         case TP_CHANNEL_GROUP_CHANGE_REASON_BANNED:
2277                 if (actor_name != NULL) {
2278                         /* translators: reverse the order of these arguments
2279                          * if the banned should come before the banner in your locale.
2280                          */
2281                         g_string_append_printf (s, _("%1$s was banned by %2$s"),
2282                                 name, actor_name);
2283                 } else {
2284                         g_string_append_printf (s, _("%s was banned"), name);
2285                 }
2286                 break;
2287         default:
2288                 g_string_append_printf (s, _("%s has left the room"), name);
2289         }
2290
2291         if (!EMP_STR_EMPTY (message)) {
2292                 /* Note to translators: this string is appended to
2293                  * notifications like "foo has left the room", with the message
2294                  * given by the user living the room. If this poses a problem,
2295                  * please let us know. :-)
2296                  */
2297                 g_string_append_printf (s, _(" (%s)"), message);
2298         }
2299
2300         return g_string_free (s, FALSE);
2301 }
2302
2303 static void
2304 chat_members_changed_cb (EmpathyTpChat  *tp_chat,
2305                          EmpathyContact *contact,
2306                          EmpathyContact *actor,
2307                          guint           reason,
2308                          gchar          *message,
2309                          gboolean        is_member,
2310                          EmpathyChat    *chat)
2311 {
2312         EmpathyChatPriv *priv = GET_PRIV (chat);
2313         const gchar *name = empathy_contact_get_alias (contact);
2314         gchar *str;
2315
2316         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED != reason);
2317
2318         if (priv->block_events_timeout_id != 0)
2319                 return;
2320
2321         if (is_member) {
2322                 str = g_strdup_printf (_("%s has joined the room"),
2323                                        name);
2324         } else {
2325                 str = build_part_message (reason, name, actor, message);
2326         }
2327
2328         empathy_chat_view_append_event (chat->view, str);
2329         g_free (str);
2330 }
2331
2332 static void
2333 chat_member_renamed_cb (EmpathyTpChat  *tp_chat,
2334                          EmpathyContact *old_contact,
2335                          EmpathyContact *new_contact,
2336                          guint           reason,
2337                          gchar          *message,
2338                          EmpathyChat    *chat)
2339 {
2340         EmpathyChatPriv *priv = GET_PRIV (chat);
2341
2342         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED == reason);
2343
2344         if (priv->block_events_timeout_id == 0) {
2345                 gchar *str;
2346
2347                 str = g_strdup_printf (_("%s is now known as %s"),
2348                                        empathy_contact_get_alias (old_contact),
2349                                        empathy_contact_get_alias (new_contact));
2350                 empathy_chat_view_append_event (chat->view, str);
2351                 g_free (str);
2352         }
2353
2354 }
2355
2356 static gboolean
2357 chat_reset_size_request (gpointer widget)
2358 {
2359         gtk_widget_set_size_request (widget, -1, -1);
2360
2361         return FALSE;
2362 }
2363
2364 static void
2365 chat_update_contacts_visibility (EmpathyChat *chat,
2366                          gboolean show)
2367 {
2368         EmpathyChatPriv *priv = GET_PRIV (chat);
2369         GtkAllocation allocation;
2370
2371         if (!priv->scrolled_window_contacts) {
2372                 return;
2373         }
2374
2375         if (priv->remote_contact != NULL) {
2376                 show = FALSE;
2377         }
2378
2379         if (show && priv->contact_list_view == NULL) {
2380                 EmpathyContactListStore *store;
2381                 gint                     min_width;
2382
2383                 /* We are adding the contact list to the chat, we don't want the
2384                  * chat view to become too small. If the chat view is already
2385                  * smaller than 250 make sure that size won't change. If the
2386                  * chat view is bigger the contact list will take some space on
2387                  * it but we make sure the chat view don't become smaller than
2388                  * 250. Relax the size request once the resize is done */
2389                 gtk_widget_get_allocation (priv->vbox_left, &allocation);
2390                 min_width = MIN (allocation.width, 250);
2391                 gtk_widget_set_size_request (priv->vbox_left, min_width, -1);
2392                 g_idle_add (chat_reset_size_request, priv->vbox_left);
2393
2394                 if (priv->contacts_width > 0) {
2395                         gtk_paned_set_position (GTK_PANED (priv->hpaned),
2396                                                 priv->contacts_width);
2397                 }
2398
2399                 store = empathy_contact_list_store_new (
2400                                 EMPATHY_CONTACT_LIST (priv->tp_chat));
2401                 empathy_contact_list_store_set_show_groups (
2402                                 EMPATHY_CONTACT_LIST_STORE (store), FALSE);
2403
2404                 priv->contact_list_view = GTK_WIDGET (empathy_contact_list_view_new (store,
2405                         EMPATHY_CONTACT_LIST_FEATURE_CONTACT_TOOLTIP,
2406                         EMPATHY_CONTACT_FEATURE_CHAT |
2407                         EMPATHY_CONTACT_FEATURE_CALL |
2408                         EMPATHY_CONTACT_FEATURE_LOG |
2409                         EMPATHY_CONTACT_FEATURE_INFO));
2410                 gtk_container_add (GTK_CONTAINER (priv->scrolled_window_contacts),
2411                                    priv->contact_list_view);
2412                 gtk_widget_show (priv->contact_list_view);
2413                 gtk_widget_show (priv->scrolled_window_contacts);
2414                 g_object_unref (store);
2415         } else if (!show) {
2416                 priv->contacts_width = gtk_paned_get_position (GTK_PANED (priv->hpaned));
2417                 gtk_widget_hide (priv->scrolled_window_contacts);
2418                 if (priv->contact_list_view != NULL) {
2419                         gtk_widget_destroy (priv->contact_list_view);
2420                         priv->contact_list_view = NULL;
2421                 }
2422         }
2423 }
2424
2425 void
2426 empathy_chat_set_show_contacts (EmpathyChat *chat,
2427                                 gboolean     show)
2428 {
2429         EmpathyChatPriv *priv = GET_PRIV (chat);
2430
2431         priv->show_contacts = show;
2432
2433         chat_update_contacts_visibility (chat, show);
2434
2435         g_object_notify (G_OBJECT (chat), "show-contacts");
2436 }
2437
2438 static void
2439 chat_remote_contact_changed_cb (EmpathyChat *chat)
2440 {
2441         EmpathyChatPriv *priv = GET_PRIV (chat);
2442
2443         if (priv->remote_contact != NULL) {
2444                 g_object_unref (priv->remote_contact);
2445                 priv->remote_contact = NULL;
2446         }
2447
2448         g_free (priv->id);
2449
2450         priv->id = g_strdup (empathy_tp_chat_get_id (priv->tp_chat));
2451         priv->remote_contact = empathy_tp_chat_get_remote_contact (priv->tp_chat);
2452         if (priv->remote_contact != NULL) {
2453                 g_object_ref (priv->remote_contact);
2454                 priv->handle_type = TP_HANDLE_TYPE_CONTACT;
2455         }
2456         else if (priv->tp_chat != NULL) {
2457                 TpChannel *channel;
2458
2459                 channel = empathy_tp_chat_get_channel (priv->tp_chat);
2460                 g_object_get (channel, "handle-type", &priv->handle_type, NULL);
2461         }
2462
2463         chat_update_contacts_visibility (chat, priv->show_contacts);
2464
2465         g_object_notify (G_OBJECT (chat), "remote-contact");
2466         g_object_notify (G_OBJECT (chat), "id");
2467 }
2468
2469 static void
2470 chat_destroy_cb (EmpathyTpChat *tp_chat,
2471                  EmpathyChat   *chat)
2472 {
2473         EmpathyChatPriv *priv;
2474
2475         priv = GET_PRIV (chat);
2476
2477         if (!priv->tp_chat) {
2478                 return;
2479         }
2480
2481         chat_composing_remove_timeout (chat);
2482         g_object_unref (priv->tp_chat);
2483         priv->tp_chat = NULL;
2484         g_object_notify (G_OBJECT (chat), "tp-chat");
2485
2486         empathy_chat_view_append_event (chat->view, _("Disconnected"));
2487         gtk_widget_set_sensitive (chat->input_text_view, FALSE);
2488
2489         chat_update_contacts_visibility (chat, FALSE);
2490 }
2491
2492 static gboolean
2493 update_misspelled_words (gpointer data)
2494 {
2495         EmpathyChat *chat = EMPATHY_CHAT (data);
2496         EmpathyChatPriv *priv = GET_PRIV (chat);
2497         GtkTextBuffer *buffer;
2498         GtkTextIter iter;
2499         gint length;
2500
2501         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2502
2503         gtk_text_buffer_get_end_iter (buffer, &iter);
2504         length = gtk_text_iter_get_offset (&iter);
2505         chat_input_text_buffer_insert_text_cb (buffer, &iter,
2506                                                NULL, length, chat);
2507
2508         priv->update_misspelled_words_id = 0;
2509
2510         return FALSE;
2511 }
2512
2513 static void
2514 conf_spell_checking_cb (GSettings *gsettings_chat,
2515                         const gchar *key,
2516                         gpointer user_data)
2517 {
2518         EmpathyChat *chat = EMPATHY_CHAT (user_data);
2519         EmpathyChatPriv *priv = GET_PRIV (chat);
2520         gboolean spell_checker;
2521         GtkTextBuffer *buffer;
2522
2523         if (strcmp (key, EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED) != 0)
2524                 return;
2525
2526         spell_checker = g_settings_get_boolean (gsettings_chat,
2527                         EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED);
2528
2529         if (!empathy_spell_supported ()) {
2530                 spell_checker = FALSE;
2531         }
2532
2533         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2534
2535         if (spell_checker == priv->spell_checking_enabled) {
2536                 if (spell_checker) {
2537                         /* Possibly changed dictionaries,
2538                          * update misspelled words. Need to do so in idle
2539                          * so the spell checker is updated. */
2540                         priv->update_misspelled_words_id =
2541                                 g_idle_add (update_misspelled_words, chat);
2542                 }
2543
2544                 return;
2545         }
2546
2547         if (spell_checker) {
2548                 GtkTextIter iter;
2549
2550                 priv->notify_cursor_position_id = tp_g_signal_connect_object  (
2551                                 buffer, "notify::cursor-position",
2552                                 G_CALLBACK (chat_input_text_buffer_notify_cursor_position_cb),
2553                                 chat, 0);
2554                 priv->insert_text_id = tp_g_signal_connect_object  (
2555                                 buffer, "insert-text",
2556                                 G_CALLBACK (chat_input_text_buffer_insert_text_cb),
2557                                 chat, G_CONNECT_AFTER);
2558                 priv->delete_range_id = tp_g_signal_connect_object  (
2559                                 buffer, "delete-range",
2560                                 G_CALLBACK (chat_input_text_buffer_delete_range_cb),
2561                                 chat, G_CONNECT_AFTER);
2562
2563                 gtk_text_buffer_create_tag (buffer, "misspelled",
2564                                             "underline", PANGO_UNDERLINE_ERROR,
2565                                             NULL);
2566
2567                 gtk_text_buffer_get_iter_at_mark (buffer, &iter,
2568                                                   gtk_text_buffer_get_insert (buffer));
2569                 gtk_text_buffer_create_mark (buffer, "previous-cursor-position",
2570                                              &iter, TRUE);
2571
2572                 /* Mark misspelled words in the existing buffer.
2573                  * Need to do so in idle so the spell checker is updated. */
2574                 priv->update_misspelled_words_id =
2575                         g_idle_add (update_misspelled_words, chat);
2576         } else {
2577                 GtkTextTagTable *table;
2578                 GtkTextTag *tag;
2579
2580                 g_signal_handler_disconnect (buffer, priv->notify_cursor_position_id);
2581                 priv->notify_cursor_position_id = 0;
2582                 g_signal_handler_disconnect (buffer, priv->insert_text_id);
2583                 priv->insert_text_id = 0;
2584                 g_signal_handler_disconnect (buffer, priv->delete_range_id);
2585                 priv->delete_range_id = 0;
2586
2587                 table = gtk_text_buffer_get_tag_table (buffer);
2588                 tag = gtk_text_tag_table_lookup (table, "misspelled");
2589                 gtk_text_tag_table_remove (table, tag);
2590
2591                 gtk_text_buffer_delete_mark_by_name (buffer,
2592                                                      "previous-cursor-position");
2593         }
2594
2595         priv->spell_checking_enabled = spell_checker;
2596 }
2597
2598 static gboolean
2599 save_paned_pos_timeout (gpointer data)
2600 {
2601         EmpathyChat *self = data;
2602         gint hpaned_pos;
2603
2604         hpaned_pos = gtk_paned_get_position (GTK_PANED (self->priv->hpaned));
2605
2606         g_settings_set_int (self->priv->gsettings_ui,
2607                             EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS,
2608                             hpaned_pos);
2609
2610         return FALSE;
2611 }
2612
2613 static gboolean
2614 chat_hpaned_pos_changed_cb (GtkWidget* hpaned,
2615                 GParamSpec *spec,
2616                 gpointer user_data)
2617 {
2618         EmpathyChat *chat = EMPATHY_CHAT (user_data);
2619
2620         if (chat->priv->save_paned_pos_id != 0)
2621                 g_source_remove (chat->priv->save_paned_pos_id);
2622
2623         chat->priv->save_paned_pos_id = g_timeout_add_seconds (1,
2624                 save_paned_pos_timeout, chat);
2625
2626         return TRUE;
2627 }
2628
2629 static void
2630 chat_create_ui (EmpathyChat *chat)
2631 {
2632         EmpathyChatPriv *priv = GET_PRIV (chat);
2633         GtkBuilder      *gui;
2634         GList           *list = NULL;
2635         gchar           *filename;
2636         GtkTextBuffer   *buffer;
2637         gint              paned_pos;
2638         EmpathyThemeManager *theme_mgr;
2639
2640         filename = empathy_file_lookup ("empathy-chat.ui",
2641                                         "libempathy-gtk");
2642         gui = empathy_builder_get_file (filename,
2643                                         "chat_widget", &priv->widget,
2644                                         "hpaned", &priv->hpaned,
2645                                         "vbox_left", &priv->vbox_left,
2646                                         "scrolled_window_chat", &priv->scrolled_window_chat,
2647                                         "scrolled_window_input", &priv->scrolled_window_input,
2648                                         "hbox_topic", &priv->hbox_topic,
2649                                         "expander_topic", &priv->expander_topic,
2650                                         "label_topic", &priv->label_topic,
2651                                         "scrolled_window_contacts", &priv->scrolled_window_contacts,
2652                                         "info_bar_vbox", &priv->info_bar_vbox,
2653                                         NULL);
2654
2655         empathy_builder_connect (gui, chat,
2656                 "expander_topic", "notify::expanded", chat_topic_expander_activate_cb,
2657                 "label_topic", "size-allocate", chat_topic_label_size_allocate_cb,
2658                 NULL);
2659
2660         g_free (filename);
2661
2662         /* Add message view. */
2663         theme_mgr = empathy_theme_manager_dup_singleton ();
2664         chat->view = empathy_theme_manager_create_view (theme_mgr);
2665         g_object_unref (theme_mgr);
2666         /* If this is a GtkTextView, it's set as a drag destination for text/plain
2667            and other types, even though it's non-editable and doesn't accept any
2668            drags.  This steals drag motion for anything inside the scrollbars,
2669            making drag destinations on chat windows far less useful.
2670          */
2671         gtk_drag_dest_unset (GTK_WIDGET (chat->view));
2672         g_signal_connect (chat->view, "focus_in_event",
2673                           G_CALLBACK (chat_text_view_focus_in_event_cb),
2674                           chat);
2675         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_chat),
2676                            GTK_WIDGET (chat->view));
2677         gtk_widget_show (GTK_WIDGET (chat->view));
2678
2679         /* Add input GtkTextView */
2680         chat->input_text_view = empathy_input_text_view_new ();
2681
2682         g_signal_connect (chat->input_text_view, "key-press-event",
2683                           G_CALLBACK (chat_input_key_press_event_cb),
2684                           chat);
2685         g_signal_connect (chat->input_text_view, "realize",
2686                           G_CALLBACK (chat_input_realize_cb),
2687                           chat);
2688         g_signal_connect (chat->input_text_view, "populate-popup",
2689                           G_CALLBACK (chat_input_populate_popup_cb),
2690                           chat);
2691         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2692         tp_g_signal_connect_object  (buffer, "changed",
2693                           G_CALLBACK (chat_input_text_buffer_changed_cb),
2694                           chat, 0);
2695         tp_g_signal_connect_object (priv->gsettings_chat,
2696                         "changed::" EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED,
2697                         G_CALLBACK (conf_spell_checking_cb), chat, 0);
2698         conf_spell_checking_cb (priv->gsettings_chat,
2699                                 EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED, chat);
2700         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_input),
2701                            chat->input_text_view);
2702         gtk_widget_show (chat->input_text_view);
2703
2704         /* Add the (invisible) search bar */
2705         priv->search_bar = empathy_search_bar_new (chat->view);
2706         gtk_box_pack_start (GTK_BOX(priv->vbox_left),
2707                             priv->search_bar,
2708                             FALSE, FALSE, 0);
2709         gtk_box_reorder_child (GTK_BOX(priv->vbox_left), priv->search_bar, 1);
2710
2711         /* Initialy hide the topic, will be shown if not empty */
2712         gtk_widget_hide (priv->hbox_topic);
2713
2714         g_signal_connect (priv->hpaned, "notify::position",
2715                           G_CALLBACK (chat_hpaned_pos_changed_cb),
2716                           chat);
2717
2718         /* Load the paned position */
2719         paned_pos = g_settings_get_int (priv->gsettings_ui,
2720                         EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS);
2721         if (paned_pos != 0)
2722                 gtk_paned_set_position (GTK_PANED(priv->hpaned), paned_pos);
2723
2724         /* Set widget focus order */
2725         list = g_list_append (NULL, priv->search_bar);
2726         list = g_list_append (list, priv->scrolled_window_input);
2727         gtk_container_set_focus_chain (GTK_CONTAINER (priv->vbox_left), list);
2728         g_list_free (list);
2729
2730         list = g_list_append (NULL, priv->vbox_left);
2731         list = g_list_append (list, priv->scrolled_window_contacts);
2732         gtk_container_set_focus_chain (GTK_CONTAINER (priv->hpaned), list);
2733         g_list_free (list);
2734
2735         list = g_list_append (NULL, priv->hpaned);
2736         list = g_list_append (list, priv->hbox_topic);
2737         gtk_container_set_focus_chain (GTK_CONTAINER (priv->widget), list);
2738         g_list_free (list);
2739
2740         /* Add the main widget in the chat widget */
2741         gtk_container_add (GTK_CONTAINER (chat), priv->widget);
2742         g_object_unref (gui);
2743 }
2744
2745 static void
2746 chat_size_allocate (GtkWidget     *widget,
2747                     GtkAllocation *allocation)
2748 {
2749   GtkBin *bin = GTK_BIN (widget);
2750   GtkAllocation child_allocation;
2751   GtkWidget *child;
2752
2753   gtk_widget_set_allocation (widget, allocation);
2754
2755   child = gtk_bin_get_child (bin);
2756
2757   if (child && gtk_widget_get_visible (child))
2758     {
2759       child_allocation.x = allocation->x + gtk_container_get_border_width (GTK_CONTAINER (widget));
2760       child_allocation.y = allocation->y + gtk_container_get_border_width (GTK_CONTAINER (widget));
2761       child_allocation.width = MAX (allocation->width - gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2, 0);
2762       child_allocation.height = MAX (allocation->height - gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2, 0);
2763
2764       gtk_widget_size_allocate (child, &child_allocation);
2765     }
2766 }
2767
2768 static void
2769 chat_finalize (GObject *object)
2770 {
2771         EmpathyChat     *chat;
2772         EmpathyChatPriv *priv;
2773
2774         chat = EMPATHY_CHAT (object);
2775         priv = GET_PRIV (chat);
2776
2777         DEBUG ("Finalized: %p", object);
2778
2779         if (priv->update_misspelled_words_id != 0)
2780                 g_source_remove (priv->update_misspelled_words_id);
2781
2782         if (priv->save_paned_pos_id != 0)
2783                 g_source_remove (priv->save_paned_pos_id);
2784
2785         g_object_unref (priv->gsettings_chat);
2786         g_object_unref (priv->gsettings_ui);
2787
2788         g_list_foreach (priv->input_history, (GFunc) chat_input_history_entry_free, NULL);
2789         g_list_free (priv->input_history);
2790
2791         g_list_foreach (priv->compositors, (GFunc) g_object_unref, NULL);
2792         g_list_free (priv->compositors);
2793
2794         chat_composing_remove_timeout (chat);
2795
2796         g_object_unref (priv->account_manager);
2797         g_object_unref (priv->log_manager);
2798
2799         if (priv->tp_chat) {
2800                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2801                         chat_destroy_cb, chat);
2802                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2803                         chat_message_received_cb, chat);
2804                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2805                         chat_send_error_cb, chat);
2806                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2807                         chat_state_changed_cb, chat);
2808                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2809                         chat_property_changed_cb, chat);
2810                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2811                         chat_members_changed_cb, chat);
2812                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2813                         chat_remote_contact_changed_cb, chat);
2814                 empathy_tp_chat_leave (priv->tp_chat, "");
2815                 g_object_unref (priv->tp_chat);
2816         }
2817         if (priv->account) {
2818                 g_object_unref (priv->account);
2819         }
2820         if (priv->remote_contact) {
2821                 g_object_unref (priv->remote_contact);
2822         }
2823
2824         if (priv->block_events_timeout_id) {
2825                 g_source_remove (priv->block_events_timeout_id);
2826         }
2827
2828         g_free (priv->id);
2829         g_free (priv->name);
2830         g_free (priv->subject);
2831         g_completion_free (priv->completion);
2832
2833         G_OBJECT_CLASS (empathy_chat_parent_class)->finalize (object);
2834 }
2835
2836 static void
2837 chat_constructed (GObject *object)
2838 {
2839         EmpathyChat *chat = EMPATHY_CHAT (object);
2840         EmpathyChatPriv *priv = GET_PRIV (chat);
2841
2842         if (priv->handle_type != TP_HANDLE_TYPE_ROOM) {
2843                 /* First display logs from the logger and then display pending messages */
2844                 chat_add_logs (chat);
2845         }
2846          else {
2847                 /* Just display pending messages for rooms */
2848                 priv->can_show_pending = TRUE;
2849                 show_pending_messages (chat);
2850         }
2851 }
2852
2853 static void
2854 empathy_chat_class_init (EmpathyChatClass *klass)
2855 {
2856         GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
2857         GObjectClass   *object_class = G_OBJECT_CLASS (klass);
2858
2859         object_class->finalize = chat_finalize;
2860         object_class->get_property = chat_get_property;
2861         object_class->set_property = chat_set_property;
2862         object_class->constructed = chat_constructed;
2863
2864         widget_class->size_allocate = chat_size_allocate;
2865
2866         g_object_class_install_property (object_class,
2867                                          PROP_TP_CHAT,
2868                                          g_param_spec_object ("tp-chat",
2869                                                               "Empathy tp chat",
2870                                                               "The tp chat object",
2871                                                               EMPATHY_TYPE_TP_CHAT,
2872                                                               G_PARAM_CONSTRUCT |
2873                                                               G_PARAM_READWRITE |
2874                                                               G_PARAM_STATIC_STRINGS));
2875         g_object_class_install_property (object_class,
2876                                          PROP_ACCOUNT,
2877                                          g_param_spec_object ("account",
2878                                                               "Account of the chat",
2879                                                               "The account of the chat",
2880                                                               TP_TYPE_ACCOUNT,
2881                                                               G_PARAM_READABLE |
2882                                                               G_PARAM_STATIC_STRINGS));
2883         g_object_class_install_property (object_class,
2884                                          PROP_ID,
2885                                          g_param_spec_string ("id",
2886                                                               "Chat's id",
2887                                                               "The id of the chat",
2888                                                               NULL,
2889                                                               G_PARAM_READABLE |
2890                                                               G_PARAM_STATIC_STRINGS));
2891         g_object_class_install_property (object_class,
2892                                          PROP_NAME,
2893                                          g_param_spec_string ("name",
2894                                                               "Chat's name",
2895                                                               "The name of the chat",
2896                                                               NULL,
2897                                                               G_PARAM_READABLE |
2898                                                               G_PARAM_STATIC_STRINGS));
2899         g_object_class_install_property (object_class,
2900                                          PROP_SUBJECT,
2901                                          g_param_spec_string ("subject",
2902                                                               "Chat's subject",
2903                                                               "The subject or topic of the chat",
2904                                                               NULL,
2905                                                               G_PARAM_READABLE |
2906                                                               G_PARAM_STATIC_STRINGS));
2907         g_object_class_install_property (object_class,
2908                                          PROP_REMOTE_CONTACT,
2909                                          g_param_spec_object ("remote-contact",
2910                                                               "The remote contact",
2911                                                               "The remote contact is any",
2912                                                               EMPATHY_TYPE_CONTACT,
2913                                                               G_PARAM_READABLE |
2914                                                               G_PARAM_STATIC_STRINGS));
2915         g_object_class_install_property (object_class,
2916                                          PROP_SHOW_CONTACTS,
2917                                          g_param_spec_boolean ("show-contacts",
2918                                                                "Contacts' visibility",
2919                                                                "The visibility of the contacts' list",
2920                                                                TRUE,
2921                                                                G_PARAM_READWRITE |
2922                                                                G_PARAM_STATIC_STRINGS));
2923
2924         signals[COMPOSING] =
2925                 g_signal_new ("composing",
2926                               G_OBJECT_CLASS_TYPE (object_class),
2927                               G_SIGNAL_RUN_LAST,
2928                               0,
2929                               NULL, NULL,
2930                               g_cclosure_marshal_VOID__BOOLEAN,
2931                               G_TYPE_NONE,
2932                               1, G_TYPE_BOOLEAN);
2933
2934         signals[NEW_MESSAGE] =
2935                 g_signal_new ("new-message",
2936                               G_OBJECT_CLASS_TYPE (object_class),
2937                               G_SIGNAL_RUN_LAST,
2938                               0,
2939                               NULL, NULL,
2940                               _empathy_gtk_marshal_VOID__OBJECT_BOOLEAN,
2941                               G_TYPE_NONE,
2942                               2, EMPATHY_TYPE_MESSAGE, G_TYPE_BOOLEAN);
2943
2944         g_type_class_add_private (object_class, sizeof (EmpathyChatPriv));
2945 }
2946
2947 static gboolean
2948 chat_block_events_timeout_cb (gpointer data)
2949 {
2950         EmpathyChatPriv *priv = GET_PRIV (data);
2951
2952         priv->block_events_timeout_id = 0;
2953
2954         return FALSE;
2955 }
2956
2957 static void
2958 account_manager_prepared_cb (GObject *source_object,
2959                              GAsyncResult *result,
2960                              gpointer user_data)
2961 {
2962         GList *accounts, *l;
2963         TpAccountManager *account_manager = TP_ACCOUNT_MANAGER (source_object);
2964         EmpathyChat *chat = user_data;
2965         GError *error = NULL;
2966
2967         if (!tp_account_manager_prepare_finish (account_manager, result, &error)) {
2968                 DEBUG ("Failed to prepare the account manager: %s", error->message);
2969                 g_error_free (error);
2970                 return;
2971         }
2972
2973         accounts = tp_account_manager_get_valid_accounts (account_manager);
2974
2975         for (l = accounts; l != NULL; l = l->next) {
2976                 TpAccount *account = l->data;
2977                 tp_g_signal_connect_object (account, "status-changed",
2978                                              G_CALLBACK (chat_new_connection_cb),
2979                                              chat, 0);
2980         }
2981
2982         g_list_free (accounts);
2983 }
2984
2985 static void
2986 empathy_chat_init (EmpathyChat *chat)
2987 {
2988         EmpathyChatPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chat,
2989                 EMPATHY_TYPE_CHAT, EmpathyChatPriv);
2990
2991         chat->priv = priv;
2992         priv->log_manager = tpl_log_manager_dup_singleton ();
2993         priv->gsettings_chat = g_settings_new (EMPATHY_PREFS_CHAT_SCHEMA);
2994         priv->gsettings_ui = g_settings_new (EMPATHY_PREFS_UI_SCHEMA);
2995
2996         priv->contacts_width = -1;
2997         priv->input_history = NULL;
2998         priv->input_history_current = NULL;
2999         priv->account_manager = tp_account_manager_dup ();
3000
3001         tp_account_manager_prepare_async (priv->account_manager, NULL,
3002                                           account_manager_prepared_cb, chat);
3003
3004         priv->show_contacts = g_settings_get_boolean (priv->gsettings_chat,
3005                         EMPATHY_PREFS_CHAT_SHOW_CONTACTS_IN_ROOMS);
3006
3007         /* Block events for some time to avoid having "has come online" or
3008          * "joined" messages. */
3009         priv->block_events_timeout_id =
3010                 g_timeout_add_seconds (1, chat_block_events_timeout_cb, chat);
3011
3012         /* Add nick name completion */
3013         priv->completion = g_completion_new ((GCompletionFunc) empathy_contact_get_alias);
3014         g_completion_set_compare (priv->completion, chat_contacts_completion_func);
3015
3016         chat_create_ui (chat);
3017 }
3018
3019 EmpathyChat *
3020 empathy_chat_new (EmpathyTpChat *tp_chat)
3021 {
3022         return g_object_new (EMPATHY_TYPE_CHAT, "tp-chat", tp_chat, NULL);
3023 }
3024
3025 EmpathyTpChat *
3026 empathy_chat_get_tp_chat (EmpathyChat *chat)
3027 {
3028         EmpathyChatPriv *priv = GET_PRIV (chat);
3029
3030         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3031
3032         return priv->tp_chat;
3033 }
3034
3035 typedef struct
3036 {
3037         EmpathyChat *self;
3038         GtkWidget *info_bar;
3039         gulong response_id;
3040         GtkWidget *button;
3041         GtkWidget *label;
3042         GtkWidget *entry;
3043         GtkWidget *spinner;
3044         gchar *password;
3045 } PasswordData;
3046
3047 static void
3048 passwd_remember_button_cb (GtkButton *button,
3049                           PasswordData *data)
3050 {
3051         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3052 }
3053
3054 static void
3055 passwd_not_now_button_cb (GtkButton *button,
3056                           PasswordData *data)
3057 {
3058         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_NO);
3059 }
3060
3061 static void
3062 remember_password_infobar_response_cb (GtkWidget *info_bar,
3063                                        gint response_id,
3064                                        PasswordData *data)
3065 {
3066         EmpathyChatPriv *priv = GET_PRIV (data->self);
3067
3068         if (response_id == GTK_RESPONSE_OK) {
3069                 DEBUG ("Saving room password");
3070                 empathy_keyring_set_room_password_async (priv->account,
3071                                                          empathy_tp_chat_get_id (priv->tp_chat),
3072                                                          data->password,
3073                                                          NULL, NULL);
3074         }
3075
3076         gtk_widget_destroy (info_bar);
3077         g_free (data->password);
3078         g_slice_free (PasswordData, data);
3079 }
3080
3081 static void
3082 chat_prompt_to_save_password (EmpathyChat *self,
3083                               PasswordData *data)
3084 {
3085         GtkWidget *content_area;
3086         GtkWidget *hbox;
3087         GtkWidget *image;
3088         GtkWidget *label;
3089         GtkWidget *alig;
3090         GtkWidget *button;
3091
3092         /* save the password in case it needs to be saved */
3093         data->password = g_strdup (gtk_entry_get_text (GTK_ENTRY (data->entry)));
3094
3095         /* Remove all previous widgets */
3096         content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (data->info_bar));
3097         gtk_container_forall (GTK_CONTAINER (content_area),
3098                               (GtkCallback) gtk_widget_destroy, NULL);
3099         data->button = NULL;
3100         data->label = NULL;
3101         data->entry = NULL;
3102         data->spinner = NULL;
3103
3104         gtk_info_bar_set_message_type (GTK_INFO_BAR (data->info_bar),
3105                                        GTK_MESSAGE_QUESTION);
3106
3107         hbox = gtk_hbox_new (FALSE, 5);
3108         gtk_box_pack_start (GTK_BOX (content_area), hbox, TRUE, TRUE, 0);
3109
3110         /* Add image */
3111         image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_AUTHENTICATION,
3112                                           GTK_ICON_SIZE_DIALOG);
3113         gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
3114
3115         /* Add message */
3116         label = gtk_label_new (_("Would you like to store this password?"));
3117         gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0);
3118
3119         /* Add 'Remember' button */
3120         alig = gtk_alignment_new (0, 0.5, 1, 0);
3121
3122         button = gtk_button_new_with_label (_("Remember"));
3123         gtk_container_add (GTK_CONTAINER (alig), button);
3124         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3125
3126         g_signal_connect (button, "clicked", G_CALLBACK (passwd_remember_button_cb),
3127                           data);
3128
3129         /* Add 'Not now' button */
3130         alig = gtk_alignment_new (0, 0.5, 1, 0);
3131
3132         button = gtk_button_new_with_label (_("Not now"));
3133         gtk_container_add (GTK_CONTAINER (alig), button);
3134         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3135
3136         g_signal_connect (button, "clicked", G_CALLBACK (passwd_not_now_button_cb),
3137                           data);
3138
3139         /* go! */
3140         g_signal_handler_disconnect (data->info_bar, data->response_id);
3141         g_signal_connect (data->info_bar, "response",
3142                           G_CALLBACK (remember_password_infobar_response_cb), data);
3143
3144         gtk_widget_show_all (data->info_bar);
3145 }
3146
3147 static void
3148 provide_password_cb (GObject *tp_chat,
3149                      GAsyncResult *res,
3150                      gpointer user_data)
3151 {
3152         PasswordData *data = user_data;
3153         EmpathyChat *self = data->self;
3154         EmpathyChatPriv *priv = GET_PRIV (self);
3155         GError *error = NULL;
3156
3157         if (!empathy_tp_chat_provide_password_finish (EMPATHY_TP_CHAT (tp_chat), res,
3158                                                       &error)) {
3159                 DEBUG ("error: %s", error->message);
3160                 /* FIXME: what should we do if that's another error? Close the channel?
3161                  * Display the raw D-Bus error to the user isn't very useful */
3162                 if (g_error_matches (error, TP_ERRORS, TP_ERROR_AUTHENTICATION_FAILED)) {
3163                         /* entry */
3164                         gtk_entry_set_text (GTK_ENTRY (data->entry), "");
3165                         gtk_widget_set_sensitive (data->entry, TRUE);
3166                         gtk_widget_grab_focus (data->entry);
3167
3168                         /* info bar */
3169                         gtk_info_bar_set_message_type (
3170                             GTK_INFO_BAR (data->info_bar),
3171                             GTK_MESSAGE_ERROR);
3172
3173                         /* button */
3174                         gtk_widget_set_sensitive (data->button, TRUE);
3175                         gtk_button_set_label (GTK_BUTTON (data->button),
3176                             _("Retry"));
3177
3178                         /* label */
3179                         gtk_label_set_text (GTK_LABEL (data->label),
3180                             _("Wrong password; please try again:"));
3181
3182                         /* spinner */
3183                         gtk_spinner_stop (GTK_SPINNER (data->spinner));
3184                         gtk_widget_hide (data->spinner);
3185                 }
3186                 g_error_free (error);
3187                 return;
3188         }
3189
3190         if (empathy_keyring_is_available ()) {
3191                 /* ask whether they want to save the password */
3192                 chat_prompt_to_save_password (self, data);
3193         } else {
3194                 /* Get rid of the password info bar finally */
3195                 gtk_widget_destroy (data->info_bar);
3196                 g_slice_free (PasswordData, data);
3197         }
3198
3199         /* Room joined */
3200         gtk_widget_set_sensitive (priv->hpaned, TRUE);
3201         gtk_widget_grab_focus (self->input_text_view);
3202 }
3203
3204 static void
3205 password_infobar_response_cb (GtkWidget *info_bar,
3206                               gint response_id,
3207                               PasswordData *data)
3208 {
3209         EmpathyChatPriv *priv = GET_PRIV (data->self);
3210         const gchar *password;
3211
3212         if (response_id != GTK_RESPONSE_OK) {
3213                 gtk_widget_destroy (info_bar);
3214                 g_slice_free (PasswordData, data);
3215                 return;
3216         }
3217
3218         password = gtk_entry_get_text (GTK_ENTRY (data->entry));
3219
3220         empathy_tp_chat_provide_password_async (priv->tp_chat, password,
3221                                                 provide_password_cb, data);
3222
3223         gtk_widget_set_sensitive (data->button, FALSE);
3224         gtk_widget_set_sensitive (data->entry, FALSE);
3225
3226         gtk_spinner_start (GTK_SPINNER (data->spinner));
3227         gtk_widget_show (data->spinner);
3228 }
3229
3230 static void
3231 password_entry_activate_cb (GtkWidget *entry,
3232                           PasswordData *data)
3233 {
3234         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3235 }
3236
3237 static void
3238 passwd_join_button_cb (GtkButton *button,
3239                           PasswordData *data)
3240 {
3241         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3242 }
3243
3244 static void
3245 clear_icon_released_cb (GtkEntry *entry,
3246                         GtkEntryIconPosition icon_pos,
3247                         GdkEvent *event,
3248                         PasswordData *data)
3249 {
3250         gtk_entry_set_text (entry, "");
3251 }
3252
3253 static void
3254 password_entry_changed_cb (GtkEditable *entry,
3255                            PasswordData *data)
3256 {
3257         const gchar *str;
3258
3259         str = gtk_entry_get_text (GTK_ENTRY (entry));
3260
3261         gtk_entry_set_icon_sensitive (GTK_ENTRY (entry),
3262             GTK_ENTRY_ICON_SECONDARY, !EMP_STR_EMPTY (str));
3263 }
3264
3265 static void
3266 display_password_info_bar (EmpathyChat *self)
3267 {
3268         EmpathyChatPriv *priv = GET_PRIV (self);
3269         GtkWidget *info_bar;
3270         GtkWidget *content_area;
3271         GtkWidget *hbox;
3272         GtkWidget *image;
3273         GtkWidget *label;
3274         GtkWidget *entry;
3275         GtkWidget *alig;
3276         GtkWidget *button;
3277         GtkWidget *spinner;
3278         PasswordData *data;
3279
3280         data = g_slice_new0 (PasswordData);
3281
3282         info_bar = gtk_info_bar_new ();
3283         gtk_info_bar_set_message_type (GTK_INFO_BAR (info_bar),
3284             GTK_MESSAGE_QUESTION);
3285
3286         content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (info_bar));
3287
3288         hbox = gtk_hbox_new (FALSE, 5);
3289         gtk_box_pack_start (GTK_BOX (content_area), hbox, TRUE, TRUE, 0);
3290
3291         /* Add image */
3292         image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_AUTHENTICATION,
3293                                           GTK_ICON_SIZE_DIALOG);
3294         gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
3295
3296         /* Add message */
3297         label = gtk_label_new (_("This room is protected by a password:"));
3298         gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);
3299
3300         /* Add password entry */
3301         entry = gtk_entry_new ();
3302         gtk_entry_set_visibility (GTK_ENTRY (entry), FALSE);
3303         gtk_box_pack_start (GTK_BOX (hbox), entry, TRUE, TRUE, 0);
3304
3305         gtk_entry_set_icon_from_stock (GTK_ENTRY (entry),
3306                                        GTK_ENTRY_ICON_SECONDARY, GTK_STOCK_CLEAR);
3307         gtk_entry_set_icon_sensitive (GTK_ENTRY (entry),
3308                                       GTK_ENTRY_ICON_SECONDARY, FALSE);
3309
3310         g_signal_connect (entry, "icon-release",
3311                           G_CALLBACK (clear_icon_released_cb), data);
3312         g_signal_connect (entry, "changed",
3313                           G_CALLBACK (password_entry_changed_cb), data);
3314
3315         g_signal_connect (entry, "activate",
3316                           G_CALLBACK (password_entry_activate_cb), data);
3317
3318         /* Focus the password entry once it's realized */
3319         g_signal_connect (entry, "realize", G_CALLBACK (gtk_widget_grab_focus), NULL);
3320
3321         /* Add 'Join' button */
3322         alig = gtk_alignment_new (0, 0.5, 1, 0);
3323
3324         button = gtk_button_new_with_label (_("Join"));
3325         gtk_container_add (GTK_CONTAINER (alig), button);
3326         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3327
3328         g_signal_connect (button, "clicked", G_CALLBACK (passwd_join_button_cb),
3329                           data);
3330
3331         /* Add spinner */
3332         spinner = gtk_spinner_new ();
3333         gtk_box_pack_end (GTK_BOX (hbox), spinner, FALSE, FALSE, 0);
3334
3335         /* Save some data for messing around with later */
3336         data->self = self;
3337         data->info_bar = info_bar;
3338         data->button = button;
3339         data->label = label;
3340         data->entry = entry;
3341         data->spinner = spinner;
3342
3343         gtk_box_pack_start (GTK_BOX (priv->info_bar_vbox), info_bar,
3344                             TRUE, TRUE, 3);
3345         gtk_widget_show_all (hbox);
3346
3347         data->response_id = g_signal_connect (info_bar, "response",
3348                                               G_CALLBACK (password_infobar_response_cb), data);
3349
3350         gtk_widget_show_all (info_bar);
3351         /* ... but hide the spinner */
3352         gtk_widget_hide (spinner);
3353 }
3354
3355 static void
3356 provide_saved_password_cb (GObject *tp_chat,
3357                            GAsyncResult *res,
3358                            gpointer user_data)
3359 {
3360         EmpathyChat *self = user_data;
3361         EmpathyChatPriv *priv = GET_PRIV (self);
3362         GError *error = NULL;
3363
3364         if (!empathy_tp_chat_provide_password_finish (EMPATHY_TP_CHAT (tp_chat), res,
3365                                                       &error)) {
3366                 DEBUG ("error: %s", error->message);
3367                 /* FIXME: what should we do if that's another error? Close the channel?
3368                  * Display the raw D-Bus error to the user isn't very useful */
3369                 if (g_error_matches (error, TP_ERRORS, TP_ERROR_AUTHENTICATION_FAILED)) {
3370                         display_password_info_bar (self);
3371                         gtk_widget_set_sensitive (priv->hpaned, FALSE);
3372                 }
3373                 g_error_free (error);
3374                 return;
3375         }
3376
3377         /* Room joined */
3378         gtk_widget_set_sensitive (priv->hpaned, TRUE);
3379         gtk_widget_grab_focus (self->input_text_view);
3380 }
3381
3382 static void
3383 chat_room_got_password_cb (GObject *source,
3384                            GAsyncResult *result,
3385                            gpointer user_data)
3386 {
3387         EmpathyChat *self = user_data;
3388         EmpathyChatPriv *priv = GET_PRIV (self);
3389         const gchar *password;
3390         GError *error = NULL;
3391
3392         password = empathy_keyring_get_room_password_finish (priv->account,
3393             result, &error);
3394
3395         if (error != NULL) {
3396                 DEBUG ("Couldn't get room password: %s\n", error->message);
3397                 g_clear_error (&error);
3398
3399                 display_password_info_bar (self);
3400                 gtk_widget_set_sensitive (priv->hpaned, FALSE);
3401                 return;
3402         }
3403
3404         empathy_tp_chat_provide_password_async (priv->tp_chat, password,
3405                                                 provide_saved_password_cb, self);
3406 }
3407
3408 static void
3409 chat_password_needed_changed_cb (EmpathyChat *self)
3410 {
3411         EmpathyChatPriv *priv = GET_PRIV (self);
3412
3413         if (empathy_tp_chat_password_needed (priv->tp_chat)) {
3414                 empathy_keyring_get_room_password_async (priv->account,
3415                                                          empathy_tp_chat_get_id (priv->tp_chat),
3416                                                          chat_room_got_password_cb, self);
3417         }
3418 }
3419
3420 void
3421 empathy_chat_set_tp_chat (EmpathyChat   *chat,
3422                           EmpathyTpChat *tp_chat)
3423 {
3424         EmpathyChatPriv *priv = GET_PRIV (chat);
3425         GPtrArray       *properties;
3426
3427         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3428         g_return_if_fail (EMPATHY_IS_TP_CHAT (tp_chat));
3429         g_return_if_fail (empathy_tp_chat_is_ready (tp_chat));
3430
3431         if (priv->tp_chat) {
3432                 return;
3433         }
3434
3435         if (priv->account) {
3436                 g_object_unref (priv->account);
3437         }
3438
3439         priv->tp_chat = g_object_ref (tp_chat);
3440         priv->account = g_object_ref (empathy_tp_chat_get_account (priv->tp_chat));
3441
3442         g_signal_connect (tp_chat, "destroy",
3443                           G_CALLBACK (chat_destroy_cb),
3444                           chat);
3445         g_signal_connect (tp_chat, "message-received",
3446                           G_CALLBACK (chat_message_received_cb),
3447                           chat);
3448         g_signal_connect (tp_chat, "send-error",
3449                           G_CALLBACK (chat_send_error_cb),
3450                           chat);
3451         g_signal_connect (tp_chat, "chat-state-changed",
3452                           G_CALLBACK (chat_state_changed_cb),
3453                           chat);
3454         g_signal_connect (tp_chat, "property-changed",
3455                           G_CALLBACK (chat_property_changed_cb),
3456                           chat);
3457         g_signal_connect (tp_chat, "members-changed",
3458                           G_CALLBACK (chat_members_changed_cb),
3459                           chat);
3460         g_signal_connect (tp_chat, "member-renamed",
3461                           G_CALLBACK (chat_member_renamed_cb),
3462                           chat);
3463         g_signal_connect_swapped (tp_chat, "notify::remote-contact",
3464                                   G_CALLBACK (chat_remote_contact_changed_cb),
3465                                   chat);
3466         g_signal_connect_swapped (tp_chat, "notify::password-needed",
3467                                   G_CALLBACK (chat_password_needed_changed_cb),
3468                                   chat);
3469
3470         /* Get initial value of properties */
3471         properties = empathy_tp_chat_get_properties (priv->tp_chat);
3472         if (properties != NULL) {
3473                 guint i;
3474
3475                 for (i = 0; i < properties->len; i++) {
3476                         EmpathyTpChatProperty *property;
3477
3478                         property = g_ptr_array_index (properties, i);
3479                         if (property->value == NULL)
3480                                 continue;
3481
3482                         chat_property_changed_cb (priv->tp_chat,
3483                                                   property->name,
3484                                                   property->value,
3485                                                   chat);
3486                 }
3487         }
3488
3489         chat_remote_contact_changed_cb (chat);
3490
3491         if (chat->input_text_view) {
3492                 gtk_widget_set_sensitive (chat->input_text_view, TRUE);
3493                 if (priv->block_events_timeout_id == 0) {
3494                         empathy_chat_view_append_event (chat->view, _("Connected"));
3495                 }
3496         }
3497
3498         g_object_notify (G_OBJECT (chat), "tp-chat");
3499         g_object_notify (G_OBJECT (chat), "id");
3500         g_object_notify (G_OBJECT (chat), "account");
3501
3502         /* This is a noop when tp-chat is set at object construction time and causes
3503          * the pending messages to be show when it's set on the object after it has
3504          * been created */
3505         show_pending_messages (chat);
3506
3507         /* check if a password is needed */
3508         chat_password_needed_changed_cb (chat);
3509 }
3510
3511 TpAccount *
3512 empathy_chat_get_account (EmpathyChat *chat)
3513 {
3514         EmpathyChatPriv *priv = GET_PRIV (chat);
3515
3516         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3517
3518         return priv->account;
3519 }
3520
3521 const gchar *
3522 empathy_chat_get_id (EmpathyChat *chat)
3523 {
3524         EmpathyChatPriv *priv = GET_PRIV (chat);
3525
3526         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3527
3528         return priv->id;
3529 }
3530
3531 const gchar *
3532 empathy_chat_get_name (EmpathyChat *chat)
3533 {
3534         EmpathyChatPriv *priv = GET_PRIV (chat);
3535         const gchar *ret;
3536
3537         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3538
3539         ret = priv->name;
3540         if (!ret && priv->remote_contact) {
3541                 ret = empathy_contact_get_alias (priv->remote_contact);
3542         }
3543
3544         if (!ret)
3545                 ret = priv->id;
3546
3547         return ret ? ret : _("Conversation");
3548 }
3549
3550 const gchar *
3551 empathy_chat_get_subject (EmpathyChat *chat)
3552 {
3553         EmpathyChatPriv *priv = GET_PRIV (chat);
3554
3555         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3556
3557         return priv->subject;
3558 }
3559
3560 EmpathyContact *
3561 empathy_chat_get_remote_contact (EmpathyChat *chat)
3562 {
3563         EmpathyChatPriv *priv = GET_PRIV (chat);
3564
3565         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3566
3567         return priv->remote_contact;
3568 }
3569
3570 GtkWidget *
3571 empathy_chat_get_contact_menu (EmpathyChat *chat)
3572 {
3573         EmpathyChatPriv *priv = GET_PRIV (chat);
3574         GtkWidget       *menu = NULL;
3575
3576         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3577
3578         if (priv->remote_contact) {
3579                 menu = empathy_contact_menu_new (priv->remote_contact,
3580                                                  EMPATHY_CONTACT_FEATURE_CALL |
3581                                                  EMPATHY_CONTACT_FEATURE_LOG |
3582                                                  EMPATHY_CONTACT_FEATURE_INFO |
3583                                                  EMPATHY_CONTACT_FEATURE_BLOCK);
3584         }
3585
3586         return menu;
3587 }
3588
3589 void
3590 empathy_chat_clear (EmpathyChat *chat)
3591 {
3592         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3593
3594         empathy_chat_view_clear (chat->view);
3595 }
3596
3597 void
3598 empathy_chat_scroll_down (EmpathyChat *chat)
3599 {
3600         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3601
3602         empathy_chat_view_scroll_down (chat->view);
3603 }
3604
3605 void
3606 empathy_chat_cut (EmpathyChat *chat)
3607 {
3608         GtkTextBuffer *buffer;
3609
3610         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3611
3612         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3613         if (gtk_text_buffer_get_has_selection (buffer)) {
3614                 GtkClipboard *clipboard;
3615
3616                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3617
3618                 gtk_text_buffer_cut_clipboard (buffer, clipboard, TRUE);
3619         }
3620 }
3621
3622 void
3623 empathy_chat_copy (EmpathyChat *chat)
3624 {
3625         GtkTextBuffer *buffer;
3626
3627         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3628
3629         if (empathy_chat_view_get_has_selection (chat->view)) {
3630                 empathy_chat_view_copy_clipboard (chat->view);
3631                 return;
3632         }
3633
3634         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3635         if (gtk_text_buffer_get_has_selection (buffer)) {
3636                 GtkClipboard *clipboard;
3637
3638                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3639
3640                 gtk_text_buffer_copy_clipboard (buffer, clipboard);
3641         }
3642         else {
3643                 gint start_offset;
3644                 gint end_offset;
3645                 EmpathyChatPriv *priv = GET_PRIV (chat);
3646
3647                 if (gtk_label_get_selection_bounds (GTK_LABEL (priv->label_topic),
3648                                                                &start_offset,
3649                                                                &end_offset)) {
3650                         gchar *start;
3651                         gchar *end;
3652                         gchar *selection;
3653                         const gchar *topic;
3654                         GtkClipboard *clipboard;
3655
3656                         topic = gtk_label_get_text (GTK_LABEL (priv->label_topic));
3657                         start = g_utf8_offset_to_pointer (topic, start_offset);
3658                         end = g_utf8_offset_to_pointer (topic, end_offset);
3659                         selection = g_strndup (start, end - start);
3660
3661                         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3662                         gtk_clipboard_set_text (clipboard, selection, -1);
3663
3664                         g_free (selection);
3665                 }
3666         }
3667 }
3668
3669 void
3670 empathy_chat_paste (EmpathyChat *chat)
3671 {
3672         GtkTextBuffer *buffer;
3673         GtkClipboard  *clipboard;
3674         EmpathyChatPriv *priv;
3675
3676         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3677
3678         priv = GET_PRIV (chat);
3679
3680         if (gtk_widget_get_visible (priv->search_bar)) {
3681                 empathy_search_bar_paste_clipboard (EMPATHY_SEARCH_BAR (priv->search_bar));
3682                 return;
3683         }
3684
3685         if (priv->tp_chat == NULL ||
3686             !gtk_widget_is_sensitive (chat->input_text_view))
3687                 return;
3688
3689         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3690         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3691
3692         gtk_text_buffer_paste_clipboard (buffer, clipboard, NULL, TRUE);
3693 }
3694
3695 void
3696 empathy_chat_find (EmpathyChat *chat)
3697 {
3698         EmpathyChatPriv *priv;
3699
3700         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3701
3702         priv = GET_PRIV (chat);
3703
3704         empathy_search_bar_show (EMPATHY_SEARCH_BAR (priv->search_bar));
3705 }
3706
3707 void
3708 empathy_chat_correct_word (EmpathyChat  *chat,
3709                           GtkTextIter *start,
3710                           GtkTextIter *end,
3711                           const gchar *new_word)
3712 {
3713         GtkTextBuffer *buffer;
3714
3715         g_return_if_fail (chat != NULL);
3716         g_return_if_fail (new_word != NULL);
3717
3718         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3719
3720         gtk_text_buffer_delete (buffer, start, end);
3721         gtk_text_buffer_insert (buffer, start,
3722                                 new_word,
3723                                 -1);
3724 }
3725
3726 gboolean
3727 empathy_chat_is_room (EmpathyChat *chat)
3728 {
3729         EmpathyChatPriv *priv = GET_PRIV (chat);
3730
3731         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
3732
3733         return (priv->handle_type == TP_HANDLE_TYPE_ROOM);
3734 }
3735
3736 guint
3737 empathy_chat_get_nb_unread_messages (EmpathyChat *self)
3738 {
3739         EmpathyChatPriv *priv = GET_PRIV (self);
3740
3741         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
3742
3743         return priv->unread_messages;
3744 }
3745
3746 /* called when the messages have been read by user */
3747 void
3748 empathy_chat_messages_read (EmpathyChat *self)
3749 {
3750         EmpathyChatPriv *priv = GET_PRIV (self);
3751
3752         g_return_if_fail (EMPATHY_IS_CHAT (self));
3753
3754         /* FIXME: See Bug#610994, See comments about it in EmpathyChatPriv
3755          * definition. If we are still retrieving the backlogs, do not ACK */
3756         if (priv->retrieving_backlogs)
3757                 return;
3758
3759         if (priv->tp_chat != NULL ) {
3760                         empathy_tp_chat_acknowledge_all_messages (priv->tp_chat);
3761         }
3762         priv->unread_messages = 0;
3763 }
3764
3765 /* Return TRUE if on of the contacts in this chat is composing */
3766 gboolean
3767 empathy_chat_is_composing (EmpathyChat *chat)
3768 {
3769   return chat->priv->compositors != NULL;
3770 }