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