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