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