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