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