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