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