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