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