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