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