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