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