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