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