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