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