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