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