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