]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-chat.c
empathy-chat: abort got_filtered_messages_cb if object was destroyed
[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         EmpathyChat *chat = user_data;
2500         EmpathyMessage *message;
2501         EmpathyChatPriv *priv = GET_PRIV (chat);
2502         const GList *pending;
2503
2504         g_return_val_if_fail (TPL_IS_EVENT (event), FALSE);
2505         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
2506
2507         pending = empathy_tp_chat_get_pending_messages (priv->tp_chat);
2508         message = empathy_message_from_tpl_log_event (event);
2509
2510         for (; pending; pending = g_list_next (pending)) {
2511                 if (empathy_message_equal (message, pending->data)) {
2512                         g_object_unref (message);
2513                         return FALSE;
2514                 }
2515         }
2516
2517         g_object_unref (message);
2518         return TRUE;
2519 }
2520
2521
2522 static void
2523 show_pending_messages (EmpathyChat *chat) {
2524         EmpathyChatPriv *priv = GET_PRIV (chat);
2525         const GList *messages, *l;
2526
2527         g_return_if_fail (EMPATHY_IS_CHAT (chat));
2528
2529         if (chat->view == NULL || priv->tp_chat == NULL)
2530                 return;
2531
2532         if (!priv->can_show_pending)
2533                 return;
2534
2535         messages = empathy_tp_chat_get_pending_messages (priv->tp_chat);
2536
2537         for (l = messages; l != NULL ; l = g_list_next (l)) {
2538                 EmpathyMessage *message = EMPATHY_MESSAGE (l->data);
2539                 chat_message_received (chat, message, TRUE);
2540         }
2541 }
2542
2543
2544 static void
2545 got_filtered_messages_cb (GObject *manager,
2546                 GAsyncResult *result,
2547                 gpointer user_data)
2548 {
2549         GList *l;
2550         GList *messages;
2551         TpWeakRef *wr = user_data;
2552         EmpathyChat *chat = tp_weak_ref_dup_object (wr);
2553         EmpathyChatPriv *priv;
2554         GError *error = NULL;
2555
2556         if (chat == NULL) {
2557                 tp_weak_ref_destroy (wr);
2558                 return;
2559         }
2560
2561         priv = GET_PRIV (chat);
2562
2563         if (!tpl_log_manager_get_filtered_events_finish (TPL_LOG_MANAGER (manager),
2564                 result, &messages, &error)) {
2565                 DEBUG ("%s. Aborting.", error->message);
2566                 empathy_chat_view_append_event (chat->view,
2567                         _("Failed to retrieve recent logs"));
2568                 g_error_free (error);
2569                 goto out;
2570         }
2571
2572         for (l = messages; l; l = g_list_next (l)) {
2573                 EmpathyMessage *message;
2574
2575                 g_assert (TPL_IS_EVENT (l->data));
2576
2577                 message = empathy_message_from_tpl_log_event (l->data);
2578                 g_object_unref (l->data);
2579
2580                 if (empathy_message_is_edit (message)) {
2581                         /* this is an edited message, create a synthetic event
2582                          * using the supersedes token and
2583                          * original-message-sent timestamp, that we can then
2584                          * replace */
2585                         EmpathyMessage *syn_msg = g_object_new (
2586                                 EMPATHY_TYPE_MESSAGE,
2587                                 "body", "",
2588                                 "token", empathy_message_get_supersedes (message),
2589                                 "type", empathy_message_get_tptype (message),
2590                                 "timestamp", empathy_message_get_original_timestamp (message),
2591                                 "incoming", empathy_message_is_incoming (message),
2592                                 "is-backlog", TRUE,
2593                                 "receiver", empathy_message_get_receiver (message),
2594                                 "sender", empathy_message_get_sender (message),
2595                                 NULL);
2596
2597                         empathy_chat_view_append_message (chat->view, syn_msg,
2598                                                           chat_should_highlight (chat, syn_msg));
2599                         empathy_chat_view_edit_message (chat->view, message);
2600
2601                         g_object_unref (syn_msg);
2602                 } else {
2603                         /* append the latest message */
2604                         empathy_chat_view_append_message (chat->view, message,
2605                                                           chat_should_highlight (chat, message));
2606                 }
2607
2608                 g_object_unref (message);
2609         }
2610         g_list_free (messages);
2611
2612 out:
2613         /* in case of TPL error, skip backlog and show pending messages */
2614         priv->can_show_pending = TRUE;
2615         show_pending_messages (chat);
2616
2617         /* FIXME: See Bug#610994, we are forcing the ACK of the queue. See comments
2618          * about it in EmpathyChatPriv definition */
2619         priv->retrieving_backlogs = FALSE;
2620         empathy_chat_messages_read (chat);
2621
2622         /* Turn back on scrolling */
2623         empathy_chat_view_scroll (chat->view, TRUE);
2624
2625         g_object_unref (chat);
2626         tp_weak_ref_destroy (wr);
2627 }
2628
2629 static void
2630 chat_add_logs (EmpathyChat *chat)
2631 {
2632         EmpathyChatPriv *priv = GET_PRIV (chat);
2633         TplEntity       *target;
2634
2635         if (!priv->id) {
2636                 return;
2637         }
2638
2639         /* Turn off scrolling temporarily */
2640         empathy_chat_view_scroll (chat->view, FALSE);
2641
2642         /* Add messages from last conversation */
2643         if (priv->handle_type == TP_HANDLE_TYPE_ROOM)
2644           target = tpl_entity_new_from_room_id (priv->id);
2645         else
2646           target = tpl_entity_new (priv->id, TPL_ENTITY_CONTACT, NULL, NULL);
2647
2648         priv->retrieving_backlogs = TRUE;
2649         tpl_log_manager_get_filtered_events_async (priv->log_manager,
2650                                                    priv->account,
2651                                                    target,
2652                                                    TPL_EVENT_MASK_TEXT,
2653                                                    5,
2654                                                    chat_log_filter,
2655                                                    chat,
2656                                                    got_filtered_messages_cb,
2657                                                    tp_weak_ref_new (chat, NULL, NULL));
2658
2659         g_object_unref (target);
2660 }
2661
2662 static gint
2663 chat_contacts_completion_func (const gchar *s1,
2664                                const gchar *s2,
2665                                gsize        n)
2666 {
2667         gchar *tmp, *nick1, *nick2;
2668         gint   ret;
2669
2670         if (s1 == s2) {
2671                 return 0;
2672         }
2673         if (!s1 || !s2) {
2674                 return s1 ? -1 : +1;
2675         }
2676
2677         tmp = g_utf8_normalize (s1, -1, G_NORMALIZE_DEFAULT);
2678         nick1 = g_utf8_casefold (tmp, -1);
2679         g_free (tmp);
2680
2681         tmp = g_utf8_normalize (s2, -1, G_NORMALIZE_DEFAULT);
2682         nick2 = g_utf8_casefold (tmp, -1);
2683         g_free (tmp);
2684
2685         ret = strncmp (nick1, nick2, n);
2686
2687         g_free (nick1);
2688         g_free (nick2);
2689
2690         return ret;
2691 }
2692
2693 static gchar *
2694 build_part_message (guint           reason,
2695                     const gchar    *name,
2696                     EmpathyContact *actor,
2697                     const gchar    *message)
2698 {
2699         GString *s = g_string_new ("");
2700         const gchar *actor_name = NULL;
2701
2702         if (actor != NULL) {
2703                 actor_name = empathy_contact_get_alias (actor);
2704         }
2705
2706         /* Having an actor only really makes sense for a few actions... */
2707         switch (reason) {
2708         case TP_CHANNEL_GROUP_CHANGE_REASON_OFFLINE:
2709                 g_string_append_printf (s, _("%s has disconnected"), name);
2710                 break;
2711         case TP_CHANNEL_GROUP_CHANGE_REASON_KICKED:
2712                 if (actor_name != NULL) {
2713                         /* translators: reverse the order of these arguments
2714                          * if the kicked should come before the kicker in your locale.
2715                          */
2716                         g_string_append_printf (s, _("%1$s was kicked by %2$s"),
2717                                 name, actor_name);
2718                 } else {
2719                         g_string_append_printf (s, _("%s was kicked"), name);
2720                 }
2721                 break;
2722         case TP_CHANNEL_GROUP_CHANGE_REASON_BANNED:
2723                 if (actor_name != NULL) {
2724                         /* translators: reverse the order of these arguments
2725                          * if the banned should come before the banner in your locale.
2726                          */
2727                         g_string_append_printf (s, _("%1$s was banned by %2$s"),
2728                                 name, actor_name);
2729                 } else {
2730                         g_string_append_printf (s, _("%s was banned"), name);
2731                 }
2732                 break;
2733         default:
2734                 g_string_append_printf (s, _("%s has left the room"), name);
2735         }
2736
2737         if (!EMP_STR_EMPTY (message)) {
2738                 /* Note to translators: this string is appended to
2739                  * notifications like "foo has left the room", with the message
2740                  * given by the user living the room. If this poses a problem,
2741                  * please let us know. :-)
2742                  */
2743                 g_string_append_printf (s, _(" (%s)"), message);
2744         }
2745
2746         return g_string_free (s, FALSE);
2747 }
2748
2749 static void
2750 chat_members_changed_cb (EmpathyTpChat  *tp_chat,
2751                          EmpathyContact *contact,
2752                          EmpathyContact *actor,
2753                          guint           reason,
2754                          gchar          *message,
2755                          gboolean        is_member,
2756                          EmpathyChat    *chat)
2757 {
2758         EmpathyChatPriv *priv = GET_PRIV (chat);
2759         const gchar *name = empathy_contact_get_alias (contact);
2760         gchar *str;
2761
2762         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED != reason);
2763
2764         if (priv->block_events_timeout_id != 0)
2765                 return;
2766
2767         if (is_member) {
2768                 str = g_strdup_printf (_("%s has joined the room"),
2769                                        name);
2770         } else {
2771                 str = build_part_message (reason, name, actor, message);
2772         }
2773
2774         empathy_chat_view_append_event (chat->view, str);
2775         g_free (str);
2776 }
2777
2778 static void
2779 chat_member_renamed_cb (EmpathyTpChat  *tp_chat,
2780                          EmpathyContact *old_contact,
2781                          EmpathyContact *new_contact,
2782                          guint           reason,
2783                          gchar          *message,
2784                          EmpathyChat    *chat)
2785 {
2786         EmpathyChatPriv *priv = GET_PRIV (chat);
2787
2788         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED == reason);
2789
2790         if (priv->block_events_timeout_id == 0) {
2791                 gchar *str;
2792
2793                 str = g_strdup_printf (_("%s is now known as %s"),
2794                                        empathy_contact_get_alias (old_contact),
2795                                        empathy_contact_get_alias (new_contact));
2796                 empathy_chat_view_append_event (chat->view, str);
2797                 g_free (str);
2798         }
2799
2800 }
2801
2802 static gboolean
2803 chat_contacts_visible_timeout_cb (gpointer chat)
2804 {
2805         EmpathyChatPriv *priv = GET_PRIV (chat);
2806
2807         /* Relax the size request */
2808         gtk_widget_set_size_request (priv->vbox_left, -1, -1);
2809
2810         /* Set the position of the slider. This must be done here because
2811          * GtkPaned need to know its size allocation and it will be settled only
2812          * after the gtk_window_resize () tough effect. */
2813         if (priv->contacts_width > 0) {
2814                 gtk_paned_set_position (GTK_PANED (priv->hpaned),
2815                                         priv->contacts_width);
2816         }
2817
2818         priv->contacts_visible_id = 0;
2819
2820         return FALSE;
2821 }
2822
2823 static void
2824 chat_update_contacts_visibility (EmpathyChat *chat,
2825                          gboolean show)
2826 {
2827         EmpathyChatPriv *priv = GET_PRIV (chat);
2828
2829         if (!priv->scrolled_window_contacts) {
2830                 return;
2831         }
2832
2833         if (priv->remote_contact != NULL) {
2834                 show = FALSE;
2835         }
2836
2837         if (show && priv->contact_list_view == NULL) {
2838                 EmpathyIndividualStore *store;
2839                 gint                     min_width;
2840                 GtkAllocation            allocation;
2841
2842                 /* We are adding the contact list to the chat, we don't want the
2843                  * chat view to become too small. If the chat view is already
2844                  * smaller than 250 make sure that size won't change. If the
2845                  * chat view is bigger the contact list will take some space on
2846                  * it but we make sure the chat view don't become smaller than
2847                  * 250. Relax the size request once the resize is done */
2848                 gtk_widget_get_allocation (priv->vbox_left, &allocation);
2849                 min_width = MIN (allocation.width, 250);
2850                 gtk_widget_set_size_request (priv->vbox_left, min_width, -1);
2851
2852                 /* There is no way to know when the window resize will happen
2853                  * since it is WM's decision. Let's hope it won't be longer. */
2854                 if (priv->contacts_visible_id != 0)
2855                         g_source_remove (priv->contacts_visible_id);
2856                 priv->contacts_visible_id = g_timeout_add (500,
2857                         chat_contacts_visible_timeout_cb, chat);
2858
2859                 store = EMPATHY_INDIVIDUAL_STORE (
2860                                 empathy_individual_store_channel_new ((TpChannel *) priv->tp_chat));
2861
2862                 empathy_individual_store_set_show_groups (store, FALSE);
2863
2864                 priv->contact_list_view = GTK_WIDGET (empathy_individual_view_new (store,
2865                         EMPATHY_INDIVIDUAL_VIEW_FEATURE_INDIVIDUAL_TOOLTIP,
2866                         EMPATHY_INDIVIDUAL_FEATURE_ADD_CONTACT |
2867                         EMPATHY_INDIVIDUAL_FEATURE_CHAT |
2868                         EMPATHY_INDIVIDUAL_FEATURE_CALL |
2869                         EMPATHY_INDIVIDUAL_FEATURE_LOG |
2870                         EMPATHY_INDIVIDUAL_FEATURE_INFO));
2871
2872                 empathy_individual_view_set_show_offline (
2873                         EMPATHY_INDIVIDUAL_VIEW (priv->contact_list_view), TRUE);
2874                 empathy_individual_view_set_show_uninteresting (
2875                         EMPATHY_INDIVIDUAL_VIEW (priv->contact_list_view), TRUE);
2876
2877                 gtk_container_add (GTK_CONTAINER (priv->scrolled_window_contacts),
2878                                    priv->contact_list_view);
2879
2880                 gtk_widget_show (priv->contact_list_view);
2881                 gtk_widget_show (priv->scrolled_window_contacts);
2882                 g_object_unref (store);
2883         } else if (!show) {
2884                 priv->contacts_width = gtk_paned_get_position (GTK_PANED (priv->hpaned));
2885                 gtk_widget_hide (priv->scrolled_window_contacts);
2886                 if (priv->contact_list_view != NULL) {
2887                         gtk_widget_destroy (priv->contact_list_view);
2888                         priv->contact_list_view = NULL;
2889                 }
2890         }
2891 }
2892
2893 void
2894 empathy_chat_set_show_contacts (EmpathyChat *chat,
2895                                 gboolean     show)
2896 {
2897         EmpathyChatPriv *priv = GET_PRIV (chat);
2898
2899         priv->show_contacts = show;
2900
2901         chat_update_contacts_visibility (chat, show);
2902
2903         g_object_notify (G_OBJECT (chat), "show-contacts");
2904 }
2905
2906 static void
2907 chat_self_contact_changed_cb (EmpathyChat *chat)
2908 {
2909         EmpathyChatPriv *priv = GET_PRIV (chat);
2910
2911         if (priv->self_contact != NULL) {
2912                 g_signal_handlers_disconnect_by_func (priv->self_contact,
2913                                                       chat_self_contact_alias_changed_cb,
2914                                                       chat);
2915         }
2916         g_clear_object (&priv->self_contact);
2917
2918         priv->self_contact = empathy_tp_chat_get_self_contact (priv->tp_chat);
2919         if (priv->self_contact != NULL) {
2920                 g_object_ref (priv->self_contact);
2921
2922                 if (empathy_chat_is_room (chat)) {
2923                         g_signal_connect_swapped (priv->self_contact, "notify::alias",
2924                                           G_CALLBACK (chat_self_contact_alias_changed_cb),
2925                                           chat);
2926                 }
2927         }
2928
2929         chat_self_contact_alias_changed_cb (chat);
2930 }
2931
2932 static void
2933 chat_remote_contact_changed_cb (EmpathyChat *chat)
2934 {
2935         EmpathyChatPriv *priv = GET_PRIV (chat);
2936
2937         if (priv->remote_contact != NULL) {
2938                 g_object_unref (priv->remote_contact);
2939                 priv->remote_contact = NULL;
2940         }
2941
2942         g_free (priv->id);
2943
2944         priv->id = g_strdup (empathy_tp_chat_get_id (priv->tp_chat));
2945         priv->remote_contact = empathy_tp_chat_get_remote_contact (priv->tp_chat);
2946         if (priv->remote_contact != NULL) {
2947                 g_object_ref (priv->remote_contact);
2948                 priv->handle_type = TP_HANDLE_TYPE_CONTACT;
2949         }
2950         else if (priv->tp_chat != NULL) {
2951                 tp_channel_get_handle ((TpChannel *) priv->tp_chat, &priv->handle_type);
2952         }
2953
2954         chat_update_contacts_visibility (chat, priv->show_contacts);
2955
2956         g_object_notify (G_OBJECT (chat), "remote-contact");
2957         g_object_notify (G_OBJECT (chat), "id");
2958 }
2959
2960 static void
2961 chat_invalidated_cb (EmpathyTpChat *tp_chat,
2962                  guint domain,
2963                  gint code,
2964                  gchar *message,
2965                  EmpathyChat   *chat)
2966 {
2967         EmpathyChatPriv *priv;
2968
2969         priv = GET_PRIV (chat);
2970
2971         if (!priv->tp_chat) {
2972                 return;
2973         }
2974
2975         chat_composing_remove_timeout (chat);
2976         g_object_unref (priv->tp_chat);
2977         priv->tp_chat = NULL;
2978         g_object_notify (G_OBJECT (chat), "tp-chat");
2979
2980         empathy_chat_view_append_event (chat->view, _("Disconnected"));
2981         gtk_widget_set_sensitive (chat->input_text_view, FALSE);
2982
2983         chat_update_contacts_visibility (chat, FALSE);
2984
2985         priv->unread_messages_when_offline = priv->unread_messages;
2986 }
2987
2988 static gboolean
2989 update_misspelled_words (gpointer data)
2990 {
2991         EmpathyChat *chat = EMPATHY_CHAT (data);
2992         EmpathyChatPriv *priv = GET_PRIV (chat);
2993         GtkTextBuffer *buffer;
2994         GtkTextIter iter;
2995         gint length;
2996
2997         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2998
2999         gtk_text_buffer_get_end_iter (buffer, &iter);
3000         length = gtk_text_iter_get_offset (&iter);
3001         chat_input_text_buffer_insert_text_cb (buffer, &iter,
3002                                                NULL, length, chat);
3003
3004         priv->update_misspelled_words_id = 0;
3005
3006         return FALSE;
3007 }
3008
3009 static void
3010 conf_spell_checking_cb (GSettings *gsettings_chat,
3011                         const gchar *key,
3012                         gpointer user_data)
3013 {
3014         EmpathyChat *chat = EMPATHY_CHAT (user_data);
3015         EmpathyChatPriv *priv = GET_PRIV (chat);
3016         gboolean spell_checker;
3017         GtkTextBuffer *buffer;
3018
3019         if (strcmp (key, EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED) != 0)
3020                 return;
3021
3022         spell_checker = g_settings_get_boolean (gsettings_chat,
3023                         EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED);
3024
3025         if (!empathy_spell_supported ()) {
3026                 spell_checker = FALSE;
3027         }
3028
3029         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3030
3031         if (spell_checker == priv->spell_checking_enabled) {
3032                 if (spell_checker) {
3033                         /* Possibly changed dictionaries,
3034                          * update misspelled words. Need to do so in idle
3035                          * so the spell checker is updated. */
3036                         priv->update_misspelled_words_id =
3037                                 g_idle_add (update_misspelled_words, chat);
3038                 }
3039
3040                 return;
3041         }
3042
3043         if (spell_checker) {
3044                 GtkTextIter iter;
3045
3046                 priv->notify_cursor_position_id = tp_g_signal_connect_object  (
3047                                 buffer, "notify::cursor-position",
3048                                 G_CALLBACK (chat_input_text_buffer_notify_cursor_position_cb),
3049                                 chat, 0);
3050                 priv->insert_text_id = tp_g_signal_connect_object  (
3051                                 buffer, "insert-text",
3052                                 G_CALLBACK (chat_input_text_buffer_insert_text_cb),
3053                                 chat, G_CONNECT_AFTER);
3054                 priv->delete_range_id = tp_g_signal_connect_object  (
3055                                 buffer, "delete-range",
3056                                 G_CALLBACK (chat_input_text_buffer_delete_range_cb),
3057                                 chat, G_CONNECT_AFTER);
3058
3059                 gtk_text_buffer_create_tag (buffer, "misspelled",
3060                                             "underline", PANGO_UNDERLINE_ERROR,
3061                                             NULL);
3062
3063                 gtk_text_buffer_get_iter_at_mark (buffer, &iter,
3064                                                   gtk_text_buffer_get_insert (buffer));
3065                 gtk_text_buffer_create_mark (buffer, "previous-cursor-position",
3066                                              &iter, TRUE);
3067
3068                 /* Mark misspelled words in the existing buffer.
3069                  * Need to do so in idle so the spell checker is updated. */
3070                 priv->update_misspelled_words_id =
3071                         g_idle_add (update_misspelled_words, chat);
3072         } else {
3073                 GtkTextTagTable *table;
3074                 GtkTextTag *tag;
3075
3076                 g_signal_handler_disconnect (buffer, priv->notify_cursor_position_id);
3077                 priv->notify_cursor_position_id = 0;
3078                 g_signal_handler_disconnect (buffer, priv->insert_text_id);
3079                 priv->insert_text_id = 0;
3080                 g_signal_handler_disconnect (buffer, priv->delete_range_id);
3081                 priv->delete_range_id = 0;
3082
3083                 table = gtk_text_buffer_get_tag_table (buffer);
3084                 tag = gtk_text_tag_table_lookup (table, "misspelled");
3085                 gtk_text_tag_table_remove (table, tag);
3086
3087                 gtk_text_buffer_delete_mark_by_name (buffer,
3088                                                      "previous-cursor-position");
3089         }
3090
3091         priv->spell_checking_enabled = spell_checker;
3092 }
3093
3094 static gboolean
3095 save_paned_pos_timeout (gpointer data)
3096 {
3097         EmpathyChat *self = data;
3098         gint hpaned_pos;
3099
3100         hpaned_pos = gtk_paned_get_position (GTK_PANED (self->priv->hpaned));
3101
3102         g_settings_set_int (self->priv->gsettings_ui,
3103                             EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS,
3104                             hpaned_pos);
3105
3106         return FALSE;
3107 }
3108
3109 static gboolean
3110 chat_hpaned_pos_changed_cb (GtkWidget* hpaned,
3111                 GParamSpec *spec,
3112                 gpointer user_data)
3113 {
3114         EmpathyChat *chat = EMPATHY_CHAT (user_data);
3115
3116         if (chat->priv->save_paned_pos_id != 0)
3117                 g_source_remove (chat->priv->save_paned_pos_id);
3118
3119         chat->priv->save_paned_pos_id = g_timeout_add_seconds (1,
3120                 save_paned_pos_timeout, chat);
3121
3122         return TRUE;
3123 }
3124
3125 static void
3126 chat_create_ui (EmpathyChat *chat)
3127 {
3128         EmpathyChatPriv *priv = GET_PRIV (chat);
3129         GtkBuilder      *gui;
3130         GList           *list = NULL;
3131         gchar           *filename;
3132         GtkTextBuffer   *buffer;
3133         EmpathyThemeManager *theme_mgr;
3134
3135         filename = empathy_file_lookup ("empathy-chat.ui",
3136                                         "libempathy-gtk");
3137         gui = empathy_builder_get_file (filename,
3138                                         "chat_widget", &priv->widget,
3139                                         "hpaned", &priv->hpaned,
3140                                         "vbox_left", &priv->vbox_left,
3141                                         "scrolled_window_chat", &priv->scrolled_window_chat,
3142                                         "scrolled_window_input", &priv->scrolled_window_input,
3143                                         "hbox_topic", &priv->hbox_topic,
3144                                         "expander_topic", &priv->expander_topic,
3145                                         "label_topic", &priv->label_topic,
3146                                         "scrolled_window_contacts", &priv->scrolled_window_contacts,
3147                                         "info_bar_vbox", &priv->info_bar_vbox,
3148                                         NULL);
3149
3150         empathy_builder_connect (gui, chat,
3151                 "expander_topic", "notify::expanded", chat_topic_expander_activate_cb,
3152                 "label_topic", "size-allocate", chat_topic_label_size_allocate_cb,
3153                 NULL);
3154
3155         g_free (filename);
3156
3157         /* Add message view. */
3158         theme_mgr = empathy_theme_manager_dup_singleton ();
3159         chat->view = empathy_theme_manager_create_view (theme_mgr);
3160         g_object_unref (theme_mgr);
3161         /* If this is a GtkTextView, it's set as a drag destination for text/plain
3162            and other types, even though it's non-editable and doesn't accept any
3163            drags.  This steals drag motion for anything inside the scrollbars,
3164            making drag destinations on chat windows far less useful.
3165          */
3166         gtk_drag_dest_unset (GTK_WIDGET (chat->view));
3167         g_signal_connect (chat->view, "focus_in_event",
3168                           G_CALLBACK (chat_text_view_focus_in_event_cb),
3169                           chat);
3170         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_chat),
3171                            GTK_WIDGET (chat->view));
3172         gtk_widget_show (GTK_WIDGET (chat->view));
3173
3174         /* Add input GtkTextView */
3175         chat->input_text_view = empathy_input_text_view_new ();
3176         g_signal_connect (chat->input_text_view, "notify::has-focus",
3177                           G_CALLBACK (chat_input_has_focus_notify_cb),
3178                           chat);
3179         g_signal_connect (chat->input_text_view, "key-press-event",
3180                           G_CALLBACK (chat_input_key_press_event_cb),
3181                           chat);
3182         g_signal_connect (chat->input_text_view, "realize",
3183                           G_CALLBACK (chat_input_realize_cb),
3184                           chat);
3185         g_signal_connect (chat->input_text_view, "button-press-event",
3186                           G_CALLBACK (chat_input_button_press_event_cb),
3187                           chat);
3188         g_signal_connect (chat->input_text_view, "populate-popup",
3189                           G_CALLBACK (chat_input_populate_popup_cb),
3190                           chat);
3191         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3192         tp_g_signal_connect_object  (buffer, "changed",
3193                           G_CALLBACK (chat_input_text_buffer_changed_cb),
3194                           chat, 0);
3195         tp_g_signal_connect_object (priv->gsettings_chat,
3196                         "changed::" EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED,
3197                         G_CALLBACK (conf_spell_checking_cb), chat, 0);
3198         conf_spell_checking_cb (priv->gsettings_chat,
3199                                 EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED, chat);
3200         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_input),
3201                            chat->input_text_view);
3202         gtk_widget_show (chat->input_text_view);
3203
3204         /* Add the (invisible) search bar */
3205         priv->search_bar = empathy_search_bar_new (chat->view);
3206         gtk_box_pack_start (GTK_BOX(priv->vbox_left),
3207                             priv->search_bar,
3208                             FALSE, FALSE, 0);
3209         gtk_box_reorder_child (GTK_BOX(priv->vbox_left), priv->search_bar, 1);
3210
3211         /* Initialy hide the topic, will be shown if not empty */
3212         gtk_widget_hide (priv->hbox_topic);
3213
3214         g_signal_connect (priv->hpaned, "notify::position",
3215                           G_CALLBACK (chat_hpaned_pos_changed_cb),
3216                           chat);
3217
3218         /* Set widget focus order */
3219         list = g_list_append (NULL, priv->search_bar);
3220         list = g_list_append (list, priv->scrolled_window_input);
3221         gtk_container_set_focus_chain (GTK_CONTAINER (priv->vbox_left), list);
3222         g_list_free (list);
3223
3224         list = g_list_append (NULL, priv->vbox_left);
3225         list = g_list_append (list, priv->scrolled_window_contacts);
3226         gtk_container_set_focus_chain (GTK_CONTAINER (priv->hpaned), list);
3227         g_list_free (list);
3228
3229         list = g_list_append (NULL, priv->hpaned);
3230         list = g_list_append (list, priv->hbox_topic);
3231         gtk_container_set_focus_chain (GTK_CONTAINER (priv->widget), list);
3232         g_list_free (list);
3233
3234         /* Add the main widget in the chat widget */
3235         gtk_box_pack_start (GTK_BOX (chat), priv->widget, TRUE, TRUE, 0);
3236         g_object_unref (gui);
3237 }
3238
3239 static void
3240 chat_finalize (GObject *object)
3241 {
3242         EmpathyChat     *chat;
3243         EmpathyChatPriv *priv;
3244
3245         chat = EMPATHY_CHAT (object);
3246         priv = GET_PRIV (chat);
3247
3248         DEBUG ("Finalized: %p", object);
3249
3250         if (priv->update_misspelled_words_id != 0)
3251                 g_source_remove (priv->update_misspelled_words_id);
3252
3253         if (priv->save_paned_pos_id != 0)
3254                 g_source_remove (priv->save_paned_pos_id);
3255
3256         if (priv->contacts_visible_id != 0)
3257                 g_source_remove (priv->contacts_visible_id);
3258
3259         g_object_unref (priv->gsettings_chat);
3260         g_object_unref (priv->gsettings_ui);
3261
3262         g_list_foreach (priv->input_history, (GFunc) chat_input_history_entry_free, NULL);
3263         g_list_free (priv->input_history);
3264
3265         g_list_foreach (priv->compositors, (GFunc) g_object_unref, NULL);
3266         g_list_free (priv->compositors);
3267
3268         chat_composing_remove_timeout (chat);
3269
3270         g_object_unref (priv->account_manager);
3271         g_object_unref (priv->log_manager);
3272
3273         if (priv->tp_chat) {
3274                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3275                         chat_invalidated_cb, chat);
3276                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3277                         chat_message_received_cb, chat);
3278                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3279                         chat_message_acknowledged_cb, chat);
3280                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3281                         chat_send_error_cb, chat);
3282                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3283                         chat_state_changed_cb, chat);
3284                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3285                         chat_members_changed_cb, chat);
3286                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3287                         chat_self_contact_changed_cb, chat);
3288                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3289                         chat_remote_contact_changed_cb, chat);
3290                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3291                         chat_title_changed_cb, chat);
3292                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3293                         chat_subject_changed_cb, chat);
3294                 empathy_tp_chat_leave (priv->tp_chat, "");
3295                 g_object_unref (priv->tp_chat);
3296         }
3297         if (priv->account) {
3298                 g_object_unref (priv->account);
3299         }
3300         if (priv->self_contact) {
3301                 g_signal_handlers_disconnect_by_func (priv->self_contact,
3302                                                       chat_self_contact_alias_changed_cb,
3303                                                       chat);
3304                 g_object_unref (priv->self_contact);
3305         }
3306         if (priv->remote_contact) {
3307                 g_object_unref (priv->remote_contact);
3308         }
3309
3310         if (priv->block_events_timeout_id) {
3311                 g_source_remove (priv->block_events_timeout_id);
3312         }
3313
3314         g_free (priv->id);
3315         g_free (priv->name);
3316         g_free (priv->subject);
3317         g_completion_free (priv->completion);
3318
3319         tp_clear_pointer (&priv->highlight_regex, g_regex_unref);
3320
3321         G_OBJECT_CLASS (empathy_chat_parent_class)->finalize (object);
3322 }
3323
3324 static void
3325 chat_constructed (GObject *object)
3326 {
3327         EmpathyChat *chat = EMPATHY_CHAT (object);
3328         EmpathyChatPriv *priv = GET_PRIV (chat);
3329
3330         if (priv->handle_type != TP_HANDLE_TYPE_ROOM) {
3331                 /* First display logs from the logger and then display pending messages */
3332                 chat_add_logs (chat);
3333         }
3334          else {
3335                 /* Just display pending messages for rooms */
3336                 priv->can_show_pending = TRUE;
3337                 show_pending_messages (chat);
3338         }
3339 }
3340
3341 static void
3342 empathy_chat_class_init (EmpathyChatClass *klass)
3343 {
3344         GObjectClass   *object_class = G_OBJECT_CLASS (klass);
3345
3346         object_class->finalize = chat_finalize;
3347         object_class->get_property = chat_get_property;
3348         object_class->set_property = chat_set_property;
3349         object_class->constructed = chat_constructed;
3350
3351         g_object_class_install_property (object_class,
3352                                          PROP_TP_CHAT,
3353                                          g_param_spec_object ("tp-chat",
3354                                                               "Empathy tp chat",
3355                                                               "The tp chat object",
3356                                                               EMPATHY_TYPE_TP_CHAT,
3357                                                               G_PARAM_CONSTRUCT |
3358                                                               G_PARAM_READWRITE |
3359                                                               G_PARAM_STATIC_STRINGS));
3360         g_object_class_install_property (object_class,
3361                                          PROP_ACCOUNT,
3362                                          g_param_spec_object ("account",
3363                                                               "Account of the chat",
3364                                                               "The account of the chat",
3365                                                               TP_TYPE_ACCOUNT,
3366                                                               G_PARAM_READABLE |
3367                                                               G_PARAM_STATIC_STRINGS));
3368         g_object_class_install_property (object_class,
3369                                          PROP_ID,
3370                                          g_param_spec_string ("id",
3371                                                               "Chat's id",
3372                                                               "The id of the chat",
3373                                                               NULL,
3374                                                               G_PARAM_READABLE |
3375                                                               G_PARAM_STATIC_STRINGS));
3376         g_object_class_install_property (object_class,
3377                                          PROP_NAME,
3378                                          g_param_spec_string ("name",
3379                                                               "Chat's name",
3380                                                               "The name of the chat",
3381                                                               NULL,
3382                                                               G_PARAM_READABLE |
3383                                                               G_PARAM_STATIC_STRINGS));
3384         g_object_class_install_property (object_class,
3385                                          PROP_SUBJECT,
3386                                          g_param_spec_string ("subject",
3387                                                               "Chat's subject",
3388                                                               "The subject or topic of the chat",
3389                                                               NULL,
3390                                                               G_PARAM_READABLE |
3391                                                               G_PARAM_STATIC_STRINGS));
3392         g_object_class_install_property (object_class,
3393                                          PROP_REMOTE_CONTACT,
3394                                          g_param_spec_object ("remote-contact",
3395                                                               "The remote contact",
3396                                                               "The remote contact is any",
3397                                                               EMPATHY_TYPE_CONTACT,
3398                                                               G_PARAM_READABLE |
3399                                                               G_PARAM_STATIC_STRINGS));
3400         g_object_class_install_property (object_class,
3401                                          PROP_SHOW_CONTACTS,
3402                                          g_param_spec_boolean ("show-contacts",
3403                                                                "Contacts' visibility",
3404                                                                "The visibility of the contacts' list",
3405                                                                TRUE,
3406                                                                G_PARAM_READWRITE |
3407                                                                G_PARAM_STATIC_STRINGS));
3408
3409         g_object_class_install_property (object_class,
3410                                          PROP_SMS_CHANNEL,
3411                                          g_param_spec_boolean ("sms-channel",
3412                                                                "SMS Channel",
3413                                                                "TRUE if this channel is for sending SMSes",
3414                                                                FALSE,
3415                                                                G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
3416
3417         g_object_class_install_property (object_class,
3418                                          PROP_N_MESSAGES_SENDING,
3419                                          g_param_spec_uint ("n-messages-sending",
3420                                                             "Num Messages Sending",
3421                                                             "The number of messages being sent",
3422                                                             0, G_MAXUINT, 0,
3423                                                             G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
3424
3425         g_object_class_install_property (object_class,
3426                                          PROP_NB_UNREAD_MESSAGES,
3427                                          g_param_spec_uint ("nb-unread-messages",
3428                                                             "Num Unread Messages",
3429                                                             "The number of unread messages",
3430                                                             0, G_MAXUINT, 0,
3431                                                             G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
3432
3433         signals[COMPOSING] =
3434                 g_signal_new ("composing",
3435                               G_OBJECT_CLASS_TYPE (object_class),
3436                               G_SIGNAL_RUN_LAST,
3437                               0,
3438                               NULL, NULL,
3439                               g_cclosure_marshal_generic,
3440                               G_TYPE_NONE,
3441                               1, G_TYPE_BOOLEAN);
3442
3443         /**
3444          * EmpathyChat::new-message:
3445          * @self: the #EmpathyChat
3446          * @message: the new message
3447          * @pending: whether the message was in the pending queue when @self
3448          *  was created
3449          * @should_highlight: %TRUE if the message mentions the local user
3450          */
3451         signals[NEW_MESSAGE] =
3452                 g_signal_new ("new-message",
3453                               G_OBJECT_CLASS_TYPE (object_class),
3454                               G_SIGNAL_RUN_LAST,
3455                               0,
3456                               NULL, NULL,
3457                               g_cclosure_marshal_generic,
3458                               G_TYPE_NONE,
3459                               3, EMPATHY_TYPE_MESSAGE, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN);
3460
3461         signals[PART_COMMAND_ENTERED] =
3462                         g_signal_new ("part-command-entered",
3463                                   G_OBJECT_CLASS_TYPE (object_class),
3464                                   G_SIGNAL_RUN_LAST,
3465                                   0,
3466                                   NULL, NULL,
3467                                   g_cclosure_marshal_generic,
3468                                   G_TYPE_NONE,
3469                                   1, G_TYPE_STRV);
3470
3471         g_type_class_add_private (object_class, sizeof (EmpathyChatPriv));
3472 }
3473
3474 static gboolean
3475 chat_block_events_timeout_cb (gpointer data)
3476 {
3477         EmpathyChatPriv *priv = GET_PRIV (data);
3478
3479         priv->block_events_timeout_id = 0;
3480
3481         return FALSE;
3482 }
3483
3484 static void
3485 account_manager_prepared_cb (GObject *source_object,
3486                              GAsyncResult *result,
3487                              gpointer user_data)
3488 {
3489         GList *accounts, *l;
3490         TpAccountManager *account_manager = TP_ACCOUNT_MANAGER (source_object);
3491         EmpathyChat *chat = user_data;
3492         GError *error = NULL;
3493
3494         if (!tp_proxy_prepare_finish (account_manager, result, &error)) {
3495                 DEBUG ("Failed to prepare the account manager: %s", error->message);
3496                 g_error_free (error);
3497                 return;
3498         }
3499
3500         accounts = tp_account_manager_get_valid_accounts (account_manager);
3501
3502         for (l = accounts; l != NULL; l = l->next) {
3503                 TpAccount *account = l->data;
3504                 tp_g_signal_connect_object (account, "status-changed",
3505                                              G_CALLBACK (chat_new_connection_cb),
3506                                              chat, 0);
3507         }
3508
3509         g_list_free (accounts);
3510 }
3511
3512 static void
3513 empathy_chat_init (EmpathyChat *chat)
3514 {
3515         EmpathyChatPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chat,
3516                 EMPATHY_TYPE_CHAT, EmpathyChatPriv);
3517
3518         chat->priv = priv;
3519         priv->log_manager = tpl_log_manager_dup_singleton ();
3520         priv->gsettings_chat = g_settings_new (EMPATHY_PREFS_CHAT_SCHEMA);
3521         priv->gsettings_ui = g_settings_new (EMPATHY_PREFS_UI_SCHEMA);
3522
3523         priv->contacts_width = g_settings_get_int (priv->gsettings_ui,
3524                 EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS);
3525         priv->input_history = NULL;
3526         priv->input_history_current = NULL;
3527         priv->account_manager = tp_account_manager_dup ();
3528
3529         tp_proxy_prepare_async (priv->account_manager, NULL,
3530                                           account_manager_prepared_cb, chat);
3531
3532         priv->show_contacts = g_settings_get_boolean (priv->gsettings_chat,
3533                         EMPATHY_PREFS_CHAT_SHOW_CONTACTS_IN_ROOMS);
3534
3535         /* Block events for some time to avoid having "has come online" or
3536          * "joined" messages. */
3537         priv->block_events_timeout_id =
3538                 g_timeout_add_seconds (1, chat_block_events_timeout_cb, chat);
3539
3540         /* Add nick name completion */
3541         priv->completion = g_completion_new ((GCompletionFunc) empathy_contact_get_alias);
3542         g_completion_set_compare (priv->completion, chat_contacts_completion_func);
3543
3544         chat_create_ui (chat);
3545 }
3546
3547 EmpathyChat *
3548 empathy_chat_new (EmpathyTpChat *tp_chat)
3549 {
3550         return g_object_new (EMPATHY_TYPE_CHAT, "tp-chat", tp_chat, NULL);
3551 }
3552
3553 EmpathyTpChat *
3554 empathy_chat_get_tp_chat (EmpathyChat *chat)
3555 {
3556         EmpathyChatPriv *priv = GET_PRIV (chat);
3557
3558         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3559
3560         return priv->tp_chat;
3561 }
3562
3563 typedef struct
3564 {
3565         EmpathyChat *self;
3566         GtkWidget *info_bar;
3567         gulong response_id;
3568         GtkWidget *button;
3569         GtkWidget *label;
3570         GtkWidget *entry;
3571         GtkWidget *spinner;
3572         gchar *password;
3573 } PasswordData;
3574
3575 static void
3576 passwd_remember_button_cb (GtkButton *button,
3577                           PasswordData *data)
3578 {
3579         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3580 }
3581
3582 static void
3583 passwd_not_now_button_cb (GtkButton *button,
3584                           PasswordData *data)
3585 {
3586         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_NO);
3587 }
3588
3589 static void
3590 remember_password_infobar_response_cb (GtkWidget *info_bar,
3591                                        gint response_id,
3592                                        PasswordData *data)
3593 {
3594         EmpathyChatPriv *priv = GET_PRIV (data->self);
3595
3596         if (response_id == GTK_RESPONSE_OK) {
3597                 DEBUG ("Saving room password");
3598                 empathy_keyring_set_room_password_async (priv->account,
3599                                                          empathy_tp_chat_get_id (priv->tp_chat),
3600                                                          data->password,
3601                                                          NULL, NULL);
3602         }
3603
3604         gtk_widget_destroy (info_bar);
3605         g_free (data->password);
3606         g_slice_free (PasswordData, data);
3607 }
3608
3609 static void
3610 chat_prompt_to_save_password (EmpathyChat *self,
3611                               PasswordData *data)
3612 {
3613         GtkWidget *content_area;
3614         GtkWidget *hbox;
3615         GtkWidget *image;
3616         GtkWidget *label;
3617         GtkWidget *alig;
3618         GtkWidget *button;
3619
3620         /* save the password in case it needs to be saved */
3621         data->password = g_strdup (gtk_entry_get_text (GTK_ENTRY (data->entry)));
3622
3623         /* Remove all previous widgets */
3624         content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (data->info_bar));
3625         gtk_container_forall (GTK_CONTAINER (content_area),
3626                               (GtkCallback) gtk_widget_destroy, NULL);
3627         data->button = NULL;
3628         data->label = NULL;
3629         data->entry = NULL;
3630         data->spinner = NULL;
3631
3632         gtk_info_bar_set_message_type (GTK_INFO_BAR (data->info_bar),
3633                                        GTK_MESSAGE_QUESTION);
3634
3635         hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 5);
3636         gtk_box_pack_start (GTK_BOX (content_area), hbox, TRUE, TRUE, 0);
3637
3638         /* Add image */
3639         image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_AUTHENTICATION,
3640                                           GTK_ICON_SIZE_DIALOG);
3641         gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
3642
3643         /* Add message */
3644         label = gtk_label_new (_("Would you like to store this password?"));
3645         gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0);
3646
3647         /* Add 'Remember' button */
3648         alig = gtk_alignment_new (0, 0.5, 1, 0);
3649
3650         button = gtk_button_new_with_label (_("Remember"));
3651         gtk_container_add (GTK_CONTAINER (alig), button);
3652         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3653
3654         g_signal_connect (button, "clicked", G_CALLBACK (passwd_remember_button_cb),
3655                           data);
3656
3657         /* Add 'Not now' button */
3658         alig = gtk_alignment_new (0, 0.5, 1, 0);
3659
3660         button = gtk_button_new_with_label (_("Not now"));
3661         gtk_container_add (GTK_CONTAINER (alig), button);
3662         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3663
3664         g_signal_connect (button, "clicked", G_CALLBACK (passwd_not_now_button_cb),
3665                           data);
3666
3667         /* go! */
3668         g_signal_handler_disconnect (data->info_bar, data->response_id);
3669         g_signal_connect (data->info_bar, "response",
3670                           G_CALLBACK (remember_password_infobar_response_cb), data);
3671
3672         gtk_widget_show_all (data->info_bar);
3673 }
3674
3675 static void
3676 provide_password_cb (GObject *tp_chat,
3677                      GAsyncResult *res,
3678                      gpointer user_data)
3679 {
3680         PasswordData *data = user_data;
3681         EmpathyChat *self = data->self;
3682         EmpathyChatPriv *priv = GET_PRIV (self);
3683         GError *error = NULL;
3684
3685         if (!tp_channel_provide_password_finish (TP_CHANNEL (tp_chat), res,
3686                                                       &error)) {
3687                 DEBUG ("error: %s", error->message);
3688                 /* FIXME: what should we do if that's another error? Close the channel?
3689                  * Display the raw D-Bus error to the user isn't very useful */
3690                 if (g_error_matches (error, TP_ERROR, TP_ERROR_AUTHENTICATION_FAILED)) {
3691                         /* entry */
3692                         gtk_entry_set_text (GTK_ENTRY (data->entry), "");
3693                         gtk_widget_set_sensitive (data->entry, TRUE);
3694                         gtk_widget_grab_focus (data->entry);
3695
3696                         /* info bar */
3697                         gtk_info_bar_set_message_type (
3698                             GTK_INFO_BAR (data->info_bar),
3699                             GTK_MESSAGE_ERROR);
3700
3701                         /* button */
3702                         gtk_widget_set_sensitive (data->button, TRUE);
3703                         gtk_button_set_label (GTK_BUTTON (data->button),
3704                             _("Retry"));
3705
3706                         /* label */
3707                         gtk_label_set_text (GTK_LABEL (data->label),
3708                             _("Wrong password; please try again:"));
3709
3710                         /* spinner */
3711                         gtk_spinner_stop (GTK_SPINNER (data->spinner));
3712                         gtk_widget_hide (data->spinner);
3713                 }
3714                 g_error_free (error);
3715                 return;
3716         }
3717
3718         if (empathy_keyring_is_available ()) {
3719                 /* ask whether they want to save the password */
3720                 chat_prompt_to_save_password (self, data);
3721         } else {
3722                 /* Get rid of the password info bar finally */
3723                 gtk_widget_destroy (data->info_bar);
3724                 g_slice_free (PasswordData, data);
3725         }
3726
3727         /* Room joined */
3728         gtk_widget_set_sensitive (priv->hpaned, TRUE);
3729         gtk_widget_set_sensitive (self->input_text_view, TRUE);
3730         gtk_widget_grab_focus (self->input_text_view);
3731 }
3732
3733 static void
3734 password_infobar_response_cb (GtkWidget *info_bar,
3735                               gint response_id,
3736                               PasswordData *data)
3737 {
3738         EmpathyChatPriv *priv = GET_PRIV (data->self);
3739         const gchar *password;
3740
3741         if (response_id != GTK_RESPONSE_OK) {
3742                 gtk_widget_destroy (info_bar);
3743                 g_slice_free (PasswordData, data);
3744                 return;
3745         }
3746
3747         password = gtk_entry_get_text (GTK_ENTRY (data->entry));
3748
3749         tp_channel_provide_password_async (TP_CHANNEL (priv->tp_chat), password,
3750                                                 provide_password_cb, data);
3751
3752         gtk_widget_set_sensitive (data->button, FALSE);
3753         gtk_widget_set_sensitive (data->entry, FALSE);
3754
3755         gtk_spinner_start (GTK_SPINNER (data->spinner));
3756         gtk_widget_show (data->spinner);
3757 }
3758
3759 static void
3760 password_entry_activate_cb (GtkWidget *entry,
3761                           PasswordData *data)
3762 {
3763         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3764 }
3765
3766 static void
3767 passwd_join_button_cb (GtkButton *button,
3768                           PasswordData *data)
3769 {
3770         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3771 }
3772
3773 static void
3774 clear_icon_released_cb (GtkEntry *entry,
3775                         GtkEntryIconPosition icon_pos,
3776                         GdkEvent *event,
3777                         PasswordData *data)
3778 {
3779         gtk_entry_set_text (entry, "");
3780 }
3781
3782 static void
3783 password_entry_changed_cb (GtkEditable *entry,
3784                            PasswordData *data)
3785 {
3786         const gchar *str;
3787
3788         str = gtk_entry_get_text (GTK_ENTRY (entry));
3789
3790         gtk_entry_set_icon_sensitive (GTK_ENTRY (entry),
3791             GTK_ENTRY_ICON_SECONDARY, !EMP_STR_EMPTY (str));
3792 }
3793
3794 static void
3795 infobar_chat_invalidated_cb (TpProxy       *proxy,
3796                            guint          domain,
3797                            gint           code,
3798                            gchar         *message,
3799                            gpointer       password_infobar)
3800 {
3801         /* Destroy the password infobar whenever a channel is invalidated
3802          * so we don't have multiple infobars when the MUC is rejoined */
3803         gtk_widget_destroy (GTK_WIDGET (password_infobar));
3804 }
3805
3806 static void
3807 display_password_info_bar (EmpathyChat *self)
3808 {
3809         EmpathyChatPriv *priv = GET_PRIV (self);
3810         GtkWidget *info_bar;
3811         GtkWidget *content_area;
3812         GtkWidget *hbox;
3813         GtkWidget *image;
3814         GtkWidget *label;
3815         GtkWidget *entry;
3816         GtkWidget *alig;
3817         GtkWidget *button;
3818         GtkWidget *spinner;
3819         PasswordData *data;
3820
3821         data = g_slice_new0 (PasswordData);
3822
3823         info_bar = gtk_info_bar_new ();
3824         gtk_info_bar_set_message_type (GTK_INFO_BAR (info_bar),
3825             GTK_MESSAGE_QUESTION);
3826
3827         content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (info_bar));
3828
3829         hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 5);
3830         gtk_box_pack_start (GTK_BOX (content_area), hbox, TRUE, TRUE, 0);
3831
3832         /* Add image */
3833         image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_AUTHENTICATION,
3834                                           GTK_ICON_SIZE_DIALOG);
3835         gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
3836
3837         /* Add message */
3838         label = gtk_label_new (_("This room is protected by a password:"));
3839         gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);
3840
3841         /* Add password entry */
3842         entry = gtk_entry_new ();
3843         gtk_entry_set_visibility (GTK_ENTRY (entry), FALSE);
3844         gtk_box_pack_start (GTK_BOX (hbox), entry, TRUE, TRUE, 0);
3845
3846         gtk_entry_set_icon_from_stock (GTK_ENTRY (entry),
3847                                        GTK_ENTRY_ICON_SECONDARY, GTK_STOCK_CLEAR);
3848         gtk_entry_set_icon_sensitive (GTK_ENTRY (entry),
3849                                       GTK_ENTRY_ICON_SECONDARY, FALSE);
3850
3851         g_signal_connect (entry, "icon-release",
3852                           G_CALLBACK (clear_icon_released_cb), data);
3853         g_signal_connect (entry, "changed",
3854                           G_CALLBACK (password_entry_changed_cb), data);
3855
3856         g_signal_connect (entry, "activate",
3857                           G_CALLBACK (password_entry_activate_cb), data);
3858
3859         /* Focus the password entry once it's realized */
3860         g_signal_connect (entry, "realize", G_CALLBACK (gtk_widget_grab_focus), NULL);
3861
3862         /* Add 'Join' button */
3863         alig = gtk_alignment_new (0, 0.5, 1, 0);
3864
3865         button = gtk_button_new_with_label (_("Join"));
3866         gtk_container_add (GTK_CONTAINER (alig), button);
3867         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3868
3869         g_signal_connect (button, "clicked", G_CALLBACK (passwd_join_button_cb),
3870                           data);
3871
3872         /* Add spinner */
3873         spinner = gtk_spinner_new ();
3874         gtk_box_pack_end (GTK_BOX (hbox), spinner, FALSE, FALSE, 0);
3875
3876         /* Save some data for messing around with later */
3877         data->self = self;
3878         data->info_bar = info_bar;
3879         data->button = button;
3880         data->label = label;
3881         data->entry = entry;
3882         data->spinner = spinner;
3883
3884         gtk_box_pack_start (GTK_BOX (priv->info_bar_vbox), info_bar,
3885                             TRUE, TRUE, 3);
3886         gtk_widget_show_all (hbox);
3887
3888         tp_g_signal_connect_object (priv->tp_chat,
3889                                   "invalidated", G_CALLBACK (infobar_chat_invalidated_cb),
3890                                   info_bar, 0);
3891
3892         data->response_id = g_signal_connect (info_bar, "response",
3893                                               G_CALLBACK (password_infobar_response_cb), data);
3894
3895         gtk_widget_show_all (info_bar);
3896         /* ... but hide the spinner */
3897         gtk_widget_hide (spinner);
3898
3899         /* prevent the user from typing anything */
3900         gtk_widget_set_sensitive (self->input_text_view, FALSE);
3901 }
3902
3903 static void
3904 provide_saved_password_cb (GObject *tp_chat,
3905                            GAsyncResult *res,
3906                            gpointer user_data)
3907 {
3908         EmpathyChat *self = user_data;
3909         EmpathyChatPriv *priv = GET_PRIV (self);
3910         GError *error = NULL;
3911
3912         if (!tp_channel_provide_password_finish (TP_CHANNEL (tp_chat), res,
3913                                                       &error)) {
3914                 DEBUG ("error: %s", error->message);
3915                 /* FIXME: what should we do if that's another error? Close the channel?
3916                  * Display the raw D-Bus error to the user isn't very useful */
3917                 if (g_error_matches (error, TP_ERROR, TP_ERROR_AUTHENTICATION_FAILED)) {
3918                         display_password_info_bar (self);
3919                         gtk_widget_set_sensitive (priv->hpaned, FALSE);
3920                 }
3921                 g_error_free (error);
3922                 return;
3923         }
3924
3925         /* Room joined */
3926         gtk_widget_set_sensitive (priv->hpaned, TRUE);
3927         gtk_widget_grab_focus (self->input_text_view);
3928 }
3929
3930 static void
3931 chat_room_got_password_cb (GObject *source,
3932                            GAsyncResult *result,
3933                            gpointer user_data)
3934 {
3935         EmpathyChat *self = user_data;
3936         EmpathyChatPriv *priv = GET_PRIV (self);
3937         const gchar *password;
3938         GError *error = NULL;
3939
3940         password = empathy_keyring_get_room_password_finish (priv->account,
3941             result, &error);
3942
3943         if (error != NULL) {
3944                 DEBUG ("Couldn't get room password: %s\n", error->message);
3945                 g_clear_error (&error);
3946
3947                 display_password_info_bar (self);
3948                 gtk_widget_set_sensitive (priv->hpaned, FALSE);
3949                 return;
3950         }
3951
3952         tp_channel_provide_password_async (TP_CHANNEL (priv->tp_chat), password,
3953                                                 provide_saved_password_cb, self);
3954 }
3955
3956 static void
3957 chat_password_needed_changed_cb (EmpathyChat *self)
3958 {
3959         EmpathyChatPriv *priv = GET_PRIV (self);
3960
3961         if (tp_channel_password_needed (TP_CHANNEL (priv->tp_chat))) {
3962                 empathy_keyring_get_room_password_async (priv->account,
3963                                                          empathy_tp_chat_get_id (priv->tp_chat),
3964                                                          chat_room_got_password_cb, self);
3965         }
3966 }
3967
3968 static void
3969 chat_sms_channel_changed_cb (EmpathyChat *self)
3970 {
3971         EmpathyChatPriv *priv = GET_PRIV (self);
3972
3973         priv->sms_channel = tp_text_channel_is_sms_channel (
3974                 (TpTextChannel *) priv->tp_chat);
3975         g_object_notify (G_OBJECT (self), "sms-channel");
3976 }
3977
3978 static void
3979 chat_n_messages_sending_changed_cb (EmpathyChat *self)
3980 {
3981         g_object_notify (G_OBJECT (self), "n-messages-sending");
3982 }
3983
3984 void
3985 empathy_chat_set_tp_chat (EmpathyChat   *chat,
3986                           EmpathyTpChat *tp_chat)
3987 {
3988         EmpathyChatPriv *priv = GET_PRIV (chat);
3989
3990         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3991         g_return_if_fail (EMPATHY_IS_TP_CHAT (tp_chat));
3992
3993         if (priv->tp_chat) {
3994                 return;
3995         }
3996
3997         if (priv->account) {
3998                 g_object_unref (priv->account);
3999         }
4000
4001         priv->tp_chat = g_object_ref (tp_chat);
4002         priv->account = g_object_ref (empathy_tp_chat_get_account (priv->tp_chat));
4003
4004         g_signal_connect (tp_chat, "invalidated",
4005                           G_CALLBACK (chat_invalidated_cb),
4006                           chat);
4007         g_signal_connect (tp_chat, "message-received-empathy",
4008                           G_CALLBACK (chat_message_received_cb),
4009                           chat);
4010         g_signal_connect (tp_chat, "message_acknowledged",
4011                           G_CALLBACK (chat_message_acknowledged_cb),
4012                           chat);
4013         g_signal_connect (tp_chat, "send-error",
4014                           G_CALLBACK (chat_send_error_cb),
4015                           chat);
4016         g_signal_connect (tp_chat, "contact-chat-state-changed",
4017                           G_CALLBACK (chat_state_changed_cb),
4018                           chat);
4019         g_signal_connect (tp_chat, "members-changed",
4020                           G_CALLBACK (chat_members_changed_cb),
4021                           chat);
4022         g_signal_connect (tp_chat, "member-renamed",
4023                           G_CALLBACK (chat_member_renamed_cb),
4024                           chat);
4025         g_signal_connect_swapped (tp_chat, "notify::self-contact",
4026                                   G_CALLBACK (chat_self_contact_changed_cb),
4027                                   chat);
4028         g_signal_connect_swapped (tp_chat, "notify::remote-contact",
4029                                   G_CALLBACK (chat_remote_contact_changed_cb),
4030                                   chat);
4031         g_signal_connect_swapped (tp_chat, "notify::password-needed",
4032                                   G_CALLBACK (chat_password_needed_changed_cb),
4033                                   chat);
4034         g_signal_connect_swapped (tp_chat, "notify::is-sms-channel",
4035                                   G_CALLBACK (chat_sms_channel_changed_cb),
4036                                   chat);
4037         g_signal_connect_swapped (tp_chat, "notify::n-messages-sending",
4038                                   G_CALLBACK (chat_n_messages_sending_changed_cb),
4039                                   chat);
4040         g_signal_connect_swapped (tp_chat, "notify::title",
4041                                   G_CALLBACK (chat_title_changed_cb),
4042                                   chat);
4043         g_signal_connect_swapped (tp_chat, "notify::subject",
4044                                   G_CALLBACK (chat_subject_changed_cb),
4045                                   chat);
4046
4047         /* Get initial value of properties */
4048         chat_sms_channel_changed_cb (chat);
4049         chat_self_contact_changed_cb (chat);
4050         chat_remote_contact_changed_cb (chat);
4051         chat_title_changed_cb (chat);
4052         chat_subject_changed_cb (chat);
4053
4054         if (chat->input_text_view) {
4055                 gtk_widget_set_sensitive (chat->input_text_view, TRUE);
4056                 if (priv->block_events_timeout_id == 0) {
4057                         empathy_chat_view_append_event (chat->view, _("Connected"));
4058                 }
4059         }
4060
4061         g_object_notify (G_OBJECT (chat), "tp-chat");
4062         g_object_notify (G_OBJECT (chat), "id");
4063         g_object_notify (G_OBJECT (chat), "account");
4064
4065         /* This is a noop when tp-chat is set at object construction time and causes
4066          * the pending messages to be show when it's set on the object after it has
4067          * been created */
4068         show_pending_messages (chat);
4069
4070         /* check if a password is needed */
4071         chat_password_needed_changed_cb (chat);
4072 }
4073
4074 TpAccount *
4075 empathy_chat_get_account (EmpathyChat *chat)
4076 {
4077         EmpathyChatPriv *priv = GET_PRIV (chat);
4078
4079         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
4080
4081         return priv->account;
4082 }
4083
4084 const gchar *
4085 empathy_chat_get_id (EmpathyChat *chat)
4086 {
4087         EmpathyChatPriv *priv = GET_PRIV (chat);
4088
4089         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
4090
4091         return priv->id;
4092 }
4093
4094 gchar *
4095 empathy_chat_dup_name (EmpathyChat *chat)
4096 {
4097         EmpathyChatPriv *priv = GET_PRIV (chat);
4098         const gchar *ret;
4099
4100         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
4101
4102         ret = priv->name;
4103
4104         if (!ret && priv->remote_contact) {
4105                 ret = empathy_contact_get_alias (priv->remote_contact);
4106         }
4107
4108         if (!ret)
4109                 ret = priv->id;
4110
4111         if (!ret)
4112                 ret = _("Conversation");
4113
4114         if (priv->sms_channel)
4115                 /* Translators: this string is a something like
4116                  * "Escher Cat (SMS)" */
4117                 return g_strdup_printf (_("%s (SMS)"), ret);
4118         else
4119                 return g_strdup (ret);
4120 }
4121
4122 const gchar *
4123 empathy_chat_get_subject (EmpathyChat *chat)
4124 {
4125         EmpathyChatPriv *priv = GET_PRIV (chat);
4126
4127         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
4128
4129         return priv->subject;
4130 }
4131
4132 EmpathyContact *
4133 empathy_chat_get_remote_contact (EmpathyChat *chat)
4134 {
4135         EmpathyChatPriv *priv = GET_PRIV (chat);
4136
4137         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
4138
4139         return priv->remote_contact;
4140 }
4141
4142 GtkWidget *
4143 empathy_chat_get_contact_menu (EmpathyChat *chat)
4144 {
4145         EmpathyChatPriv *priv = GET_PRIV (chat);
4146         GtkWidget       *menu = NULL;
4147         FolksIndividual *individual;
4148         TpContact *contact;
4149
4150         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
4151
4152         if (priv->remote_contact == NULL)
4153                 return NULL;
4154
4155         contact = empathy_contact_get_tp_contact (priv->remote_contact);
4156         if (contact == NULL)
4157                 return NULL;
4158
4159         individual = empathy_ensure_individual_from_tp_contact (contact);
4160
4161         if (individual == NULL)
4162                 return NULL;
4163
4164         menu = empathy_individual_menu_new (individual,
4165                                          EMPATHY_INDIVIDUAL_FEATURE_CALL |
4166                                          EMPATHY_INDIVIDUAL_FEATURE_LOG |
4167                                          EMPATHY_INDIVIDUAL_FEATURE_INFO |
4168                                          EMPATHY_INDIVIDUAL_FEATURE_BLOCK, NULL);
4169
4170         g_object_unref (individual);
4171
4172         return menu;
4173 }
4174
4175 void
4176 empathy_chat_clear (EmpathyChat *chat)
4177 {
4178         g_return_if_fail (EMPATHY_IS_CHAT (chat));
4179
4180         empathy_chat_view_clear (chat->view);
4181 }
4182
4183 void
4184 empathy_chat_scroll_down (EmpathyChat *chat)
4185 {
4186         g_return_if_fail (EMPATHY_IS_CHAT (chat));
4187
4188         empathy_chat_view_scroll_down (chat->view);
4189 }
4190
4191 void
4192 empathy_chat_cut (EmpathyChat *chat)
4193 {
4194         GtkTextBuffer *buffer;
4195
4196         g_return_if_fail (EMPATHY_IS_CHAT (chat));
4197
4198         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
4199         if (gtk_text_buffer_get_has_selection (buffer)) {
4200                 GtkClipboard *clipboard;
4201
4202                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
4203
4204                 gtk_text_buffer_cut_clipboard (buffer, clipboard, TRUE);
4205         }
4206 }
4207
4208 void
4209 empathy_chat_copy (EmpathyChat *chat)
4210 {
4211         GtkTextBuffer *buffer;
4212
4213         g_return_if_fail (EMPATHY_IS_CHAT (chat));
4214
4215         if (empathy_chat_view_get_has_selection (chat->view)) {
4216                 empathy_chat_view_copy_clipboard (chat->view);
4217                 return;
4218         }
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_copy_clipboard (buffer, clipboard);
4227         }
4228         else {
4229                 gint start_offset;
4230                 gint end_offset;
4231                 EmpathyChatPriv *priv = GET_PRIV (chat);
4232
4233                 if (gtk_label_get_selection_bounds (GTK_LABEL (priv->label_topic),
4234                                                                &start_offset,
4235                                                                &end_offset)) {
4236                         gchar *start;
4237                         gchar *end;
4238                         gchar *selection;
4239                         const gchar *topic;
4240                         GtkClipboard *clipboard;
4241
4242                         topic = gtk_label_get_text (GTK_LABEL (priv->label_topic));
4243                         start = g_utf8_offset_to_pointer (topic, start_offset);
4244                         end = g_utf8_offset_to_pointer (topic, end_offset);
4245                         selection = g_strndup (start, end - start);
4246
4247                         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
4248                         gtk_clipboard_set_text (clipboard, selection, -1);
4249
4250                         g_free (selection);
4251                 }
4252         }
4253 }
4254
4255 void
4256 empathy_chat_paste (EmpathyChat *chat)
4257 {
4258         GtkTextBuffer *buffer;
4259         GtkClipboard  *clipboard;
4260         EmpathyChatPriv *priv;
4261
4262         g_return_if_fail (EMPATHY_IS_CHAT (chat));
4263
4264         priv = GET_PRIV (chat);
4265
4266         if (gtk_widget_get_visible (priv->search_bar)) {
4267                 empathy_search_bar_paste_clipboard (EMPATHY_SEARCH_BAR (priv->search_bar));
4268                 return;
4269         }
4270
4271         if (priv->tp_chat == NULL ||
4272             !gtk_widget_is_sensitive (chat->input_text_view))
4273                 return;
4274
4275         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
4276         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
4277
4278         gtk_text_buffer_paste_clipboard (buffer, clipboard, NULL, TRUE);
4279 }
4280
4281 void
4282 empathy_chat_find (EmpathyChat *chat)
4283 {
4284         EmpathyChatPriv *priv;
4285
4286         g_return_if_fail (EMPATHY_IS_CHAT (chat));
4287
4288         priv = GET_PRIV (chat);
4289
4290         empathy_search_bar_show (EMPATHY_SEARCH_BAR (priv->search_bar));
4291 }
4292
4293 void
4294 empathy_chat_correct_word (EmpathyChat  *chat,
4295                           GtkTextIter *start,
4296                           GtkTextIter *end,
4297                           const gchar *new_word)
4298 {
4299         GtkTextBuffer *buffer;
4300
4301         g_return_if_fail (chat != NULL);
4302         g_return_if_fail (new_word != NULL);
4303
4304         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
4305
4306         gtk_text_buffer_delete (buffer, start, end);
4307         gtk_text_buffer_insert (buffer, start,
4308                                 new_word,
4309                                 -1);
4310 }
4311
4312 gboolean
4313 empathy_chat_is_room (EmpathyChat *chat)
4314 {
4315         EmpathyChatPriv *priv = GET_PRIV (chat);
4316
4317         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
4318
4319         return (priv->handle_type == TP_HANDLE_TYPE_ROOM);
4320 }
4321
4322 gboolean
4323 empathy_chat_is_highlighted (EmpathyChat *chat)
4324 {
4325         EmpathyChatPriv *priv = GET_PRIV (chat);
4326
4327         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
4328
4329         return priv->highlighted;
4330 }
4331
4332 guint
4333 empathy_chat_get_nb_unread_messages (EmpathyChat *self)
4334 {
4335         EmpathyChatPriv *priv = GET_PRIV (self);
4336
4337         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
4338
4339         return priv->unread_messages;
4340 }
4341
4342 /* called when the messages have been read by user */
4343 void
4344 empathy_chat_messages_read (EmpathyChat *self)
4345 {
4346         EmpathyChatPriv *priv = GET_PRIV (self);
4347
4348         g_return_if_fail (EMPATHY_IS_CHAT (self));
4349
4350         /* FIXME: See Bug#610994, See comments about it in EmpathyChatPriv
4351          * definition. If we are still retrieving the backlogs, do not ACK */
4352         if (priv->retrieving_backlogs)
4353                 return;
4354
4355         if (priv->tp_chat != NULL) {
4356                 tp_text_channel_ack_all_pending_messages_async (
4357                         TP_TEXT_CHANNEL (priv->tp_chat), NULL, NULL);
4358         }
4359
4360         priv->highlighted = FALSE;
4361
4362         if (priv->unread_messages_when_offline > 0) {
4363                 /* We can't ack those as the connection has gone away so just consider
4364                 * them as read. */
4365                 priv->unread_messages -= priv->unread_messages_when_offline;
4366                 g_object_notify (G_OBJECT (self), "nb-unread-messages");
4367                 priv->unread_messages_when_offline = 0;
4368         }
4369 }
4370
4371 /* Return TRUE if on of the contacts in this chat is composing */
4372 gboolean
4373 empathy_chat_is_composing (EmpathyChat *chat)
4374 {
4375   return chat->priv->compositors != NULL;
4376 }
4377
4378 gboolean
4379 empathy_chat_is_sms_channel (EmpathyChat *self)
4380 {
4381         EmpathyChatPriv *priv = GET_PRIV (self);
4382
4383         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
4384
4385         return priv->sms_channel;
4386 }
4387
4388 guint
4389 empathy_chat_get_n_messages_sending (EmpathyChat *self)
4390 {
4391         EmpathyChatPriv *priv;
4392
4393         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
4394
4395         priv = GET_PRIV (self);
4396
4397         if (priv->tp_chat == NULL) {
4398                 return 0;
4399         } else {
4400                 guint n_messages;
4401
4402                 g_object_get (priv->tp_chat,
4403                         "n-messages-sending", &n_messages,
4404                         NULL);
4405
4406                 return n_messages;
4407         }
4408 }
4409
4410 gchar *
4411 empathy_chat_dup_text (EmpathyChat *self)
4412 {
4413         GtkTextBuffer *buffer;
4414         GtkTextIter     start, end;
4415
4416         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (self->input_text_view));
4417
4418         gtk_text_buffer_get_bounds (buffer, &start, &end);
4419         return gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
4420 }
4421
4422 void
4423 empathy_chat_set_text (EmpathyChat *self,
4424                        const gchar *text)
4425 {
4426         GtkTextBuffer *buffer;
4427
4428         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (self->input_text_view));
4429
4430         gtk_text_buffer_set_text (buffer, text, -1);
4431 }