]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-chat.c
tp-chat: give ::pending-message-removed the message
[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         }
1282
1283         g_signal_emit (chat, signals[NEW_MESSAGE], 0, message, pending);
1284 }
1285
1286 static void
1287 chat_message_received_cb (EmpathyTpChat  *tp_chat,
1288                           EmpathyMessage *message,
1289                           EmpathyChat    *chat)
1290 {
1291         chat_message_received (chat, message, FALSE);
1292 }
1293
1294 static void
1295 chat_pending_message_removed_cb (EmpathyTpChat  *tp_chat,
1296                                  EmpathyMessage *message,
1297                                  EmpathyChat    *chat)
1298 {
1299         EmpathyChatPriv *priv = GET_PRIV (chat);
1300
1301         priv->unread_messages--;
1302         g_object_notify (G_OBJECT (chat), "nb-unread-messages");
1303 }
1304
1305 static void
1306 chat_send_error_cb (EmpathyTpChat          *tp_chat,
1307                     const gchar            *message_body,
1308                     TpChannelTextSendError  error_code,
1309                     const gchar            *dbus_error,
1310                     EmpathyChat            *chat)
1311 {
1312         const gchar *error = NULL;
1313         gchar       *str;
1314
1315         if (!tp_strdiff (dbus_error, TP_ERROR_STR_INSUFFICIENT_BALANCE)) {
1316                 /* translators: error used when user doesn't have enough credit on his
1317                  * account to send the message. */
1318                 error = _("insufficient balance to send message");
1319         } else if (!tp_strdiff (dbus_error, TP_ERROR_STR_NOT_CAPABLE)) {
1320                 error = _("not capable");
1321         }
1322
1323         if (error == NULL) {
1324                 /* if we didn't find a dbus-error, try the old error */
1325                 switch (error_code) {
1326                 case TP_CHANNEL_TEXT_SEND_ERROR_OFFLINE:
1327                         error = _("offline");
1328                         break;
1329                 case TP_CHANNEL_TEXT_SEND_ERROR_INVALID_CONTACT:
1330                         error = _("invalid contact");
1331                         break;
1332                 case TP_CHANNEL_TEXT_SEND_ERROR_PERMISSION_DENIED:
1333                         error = _("permission denied");
1334                         break;
1335                 case TP_CHANNEL_TEXT_SEND_ERROR_TOO_LONG:
1336                         error = _("too long message");
1337                         break;
1338                 case TP_CHANNEL_TEXT_SEND_ERROR_NOT_IMPLEMENTED:
1339                         error = _("not implemented");
1340                         break;
1341                 case TP_CHANNEL_TEXT_SEND_ERROR_UNKNOWN:
1342                 default:
1343                         error = _("unknown");
1344                         break;
1345                 }
1346         }
1347
1348         if (message_body != NULL) {
1349                         str = g_strdup_printf (_("Error sending message '%s': %s"),
1350                                 message_body, error);
1351         }
1352         else {
1353                         str = g_strdup_printf (_("Error sending message: %s"), error);
1354         }
1355
1356         empathy_chat_view_append_event (chat->view, str);
1357         g_free (str);
1358 }
1359
1360 static void
1361 chat_topic_label_size_allocate_cb (GtkLabel *label,
1362                                    GtkAllocation *allocation,
1363                                    EmpathyChat *chat)
1364 {
1365         EmpathyChatPriv *priv = GET_PRIV (chat);
1366
1367         if (!gtk_label_get_line_wrap (label)) {
1368                 if (pango_layout_is_ellipsized (gtk_label_get_layout (label)))
1369                         gtk_widget_show (priv->expander_topic);
1370                 else
1371                         gtk_widget_hide (priv->expander_topic);
1372
1373                 return;
1374         }
1375 }
1376
1377 static void
1378 chat_topic_expander_activate_cb (GtkExpander *expander,
1379                                  GParamSpec *param_spec,
1380                                  EmpathyChat *chat)
1381 {
1382         EmpathyChatPriv *priv = GET_PRIV (chat);
1383
1384         if (gtk_expander_get_expanded (expander)) {
1385                 gtk_label_set_ellipsize (GTK_LABEL (priv->label_topic), PANGO_ELLIPSIZE_NONE);
1386                 gtk_label_set_line_wrap (GTK_LABEL (priv->label_topic), TRUE);
1387         } else {
1388                 gtk_label_set_ellipsize (GTK_LABEL (priv->label_topic), PANGO_ELLIPSIZE_END);
1389                 gtk_label_set_line_wrap (GTK_LABEL (priv->label_topic), FALSE);
1390         }
1391 }
1392
1393 static void
1394 chat_property_changed_cb (EmpathyTpChat *tp_chat,
1395                           const gchar   *name,
1396                           GValue        *value,
1397                           EmpathyChat   *chat)
1398 {
1399         EmpathyChatPriv *priv = GET_PRIV (chat);
1400
1401         if (!tp_strdiff (name, "subject")) {
1402                 g_free (priv->subject);
1403                 priv->subject = g_value_dup_string (value);
1404                 g_object_notify (G_OBJECT (chat), "subject");
1405
1406                 if (EMP_STR_EMPTY (priv->subject)) {
1407                         gtk_widget_hide (priv->hbox_topic);
1408                 } else {
1409                         gchar *markup_topic;
1410                         gchar *markup_text;
1411
1412                         markup_topic = empathy_add_link_markup (priv->subject);
1413                         markup_text = g_strdup_printf ("<span weight=\"bold\">%s</span> %s",
1414                                 _("Topic:"), markup_topic);
1415
1416                         gtk_label_set_markup (GTK_LABEL (priv->label_topic), markup_text);
1417                         g_free (markup_text);
1418                         g_free (markup_topic);
1419
1420                         gtk_widget_show (priv->hbox_topic);
1421                 }
1422                 if (priv->block_events_timeout_id == 0) {
1423                         gchar *str;
1424
1425                         if (!EMP_STR_EMPTY (priv->subject)) {
1426                                 str = g_strdup_printf (_("Topic set to: %s"), priv->subject);
1427                         } else {
1428                                 str = g_strdup (_("No topic defined"));
1429                         }
1430                         empathy_chat_view_append_event (EMPATHY_CHAT (chat)->view, str);
1431                         g_free (str);
1432                 }
1433         }
1434         else if (!tp_strdiff (name, "name")) {
1435                 g_free (priv->name);
1436                 priv->name = g_value_dup_string (value);
1437                 g_object_notify (G_OBJECT (chat), "name");
1438         }
1439 }
1440
1441 static gboolean
1442 chat_input_text_get_word_from_iter (GtkTextIter   *iter,
1443                                     GtkTextIter   *start,
1444                                     GtkTextIter   *end)
1445 {
1446         GtkTextIter word_start = *iter;
1447         GtkTextIter word_end = *iter;
1448         GtkTextIter tmp;
1449
1450         if (gtk_text_iter_inside_word (&word_end) &&
1451                         !gtk_text_iter_ends_word (&word_end)) {
1452                 gtk_text_iter_forward_word_end (&word_end);
1453         }
1454
1455         tmp = word_end;
1456
1457         if (gtk_text_iter_get_char (&tmp) == '\'') {
1458                 gtk_text_iter_forward_char (&tmp);
1459
1460                 if (g_unichar_isalpha (gtk_text_iter_get_char (&tmp))) {
1461                         gtk_text_iter_forward_word_end (&word_end);
1462                 }
1463         }
1464
1465
1466         if (gtk_text_iter_inside_word (&word_start) ||
1467                         gtk_text_iter_ends_word (&word_start)) {
1468                 if (!gtk_text_iter_starts_word (&word_start) ||
1469                                 gtk_text_iter_equal (&word_start, &word_end)) {
1470                         gtk_text_iter_backward_word_start (&word_start);
1471                 }
1472
1473                 tmp = word_start;
1474                 gtk_text_iter_backward_char (&tmp);
1475
1476                 if (gtk_text_iter_get_char (&tmp) == '\'') {
1477                         gtk_text_iter_backward_char (&tmp);
1478
1479                         if (g_unichar_isalpha (gtk_text_iter_get_char (&tmp))) {
1480                                 gtk_text_iter_backward_word_start (&word_start);
1481                         }
1482                 }
1483         }
1484
1485         *start = word_start;
1486         *end = word_end;
1487         return TRUE;
1488 }
1489
1490 static void
1491 chat_input_text_buffer_insert_text_cb (GtkTextBuffer *buffer,
1492                                        GtkTextIter   *location,
1493                                        gchar         *text,
1494                                        gint           len,
1495                                        EmpathyChat   *chat)
1496 {
1497         GtkTextIter iter, pos;
1498
1499         /* Remove all misspelled tags in the inserted text.
1500          * This happens when text is inserted within a misspelled word. */
1501         gtk_text_buffer_get_iter_at_offset (buffer, &iter,
1502                                             gtk_text_iter_get_offset (location) - len);
1503         gtk_text_buffer_remove_tag_by_name (buffer, "misspelled",
1504                                             &iter, location);
1505
1506         gtk_text_buffer_get_iter_at_mark (buffer, &pos, gtk_text_buffer_get_insert (buffer));
1507
1508         do {
1509                 GtkTextIter start, end;
1510                 gchar *str;
1511
1512                 if (!chat_input_text_get_word_from_iter (&iter, &start, &end))
1513                         continue;
1514
1515                 str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1516
1517                 if (gtk_text_iter_in_range (&pos, &start, &end) ||
1518                                 gtk_text_iter_equal (&pos, &end) ||
1519                                 empathy_spell_check (str)) {
1520                         gtk_text_buffer_remove_tag_by_name (buffer, "misspelled", &start, &end);
1521                 } else {
1522                         gtk_text_buffer_apply_tag_by_name (buffer, "misspelled", &start, &end);
1523                 }
1524
1525                 g_free (str);
1526
1527         } while (gtk_text_iter_forward_word_end (&iter) &&
1528                  gtk_text_iter_compare (&iter, location) <= 0);
1529 }
1530
1531 static void
1532 chat_input_text_buffer_delete_range_cb (GtkTextBuffer *buffer,
1533                                         GtkTextIter   *start,
1534                                         GtkTextIter   *end,
1535                                         EmpathyChat   *chat)
1536 {
1537         GtkTextIter word_start, word_end;
1538
1539         if (chat_input_text_get_word_from_iter (start, &word_start, &word_end)) {
1540                 gtk_text_buffer_remove_tag_by_name (buffer, "misspelled",
1541                                                     &word_start, &word_end);
1542         }
1543 }
1544
1545 static void
1546 chat_input_text_buffer_changed_cb (GtkTextBuffer *buffer,
1547                                    EmpathyChat    *chat)
1548 {
1549         if (gtk_text_buffer_get_char_count (buffer) == 0) {
1550                 chat_composing_stop (chat);
1551         } else {
1552                 chat_composing_start (chat);
1553         }
1554 }
1555
1556 static void
1557 chat_input_text_buffer_notify_cursor_position_cb (GtkTextBuffer *buffer,
1558                                                   GParamSpec    *pspec,
1559                                                   EmpathyChat    *chat)
1560 {
1561         GtkTextIter pos;
1562         GtkTextIter prev_pos;
1563         GtkTextIter word_start;
1564         GtkTextIter word_end;
1565         GtkTextMark *mark;
1566         gchar *str;
1567
1568         mark = gtk_text_buffer_get_mark (buffer, "previous-cursor-position");
1569
1570         gtk_text_buffer_get_iter_at_mark (buffer, &pos,
1571                                           gtk_text_buffer_get_insert (buffer));
1572         gtk_text_buffer_get_iter_at_mark (buffer, &prev_pos, mark);
1573
1574         if (!chat_input_text_get_word_from_iter (&prev_pos, &word_start, &word_end))
1575                 goto out;
1576
1577         if (!gtk_text_iter_in_range (&pos, &word_start, &word_end) &&
1578                         !gtk_text_iter_equal (&pos, &word_end)) {
1579                 str = gtk_text_buffer_get_text (buffer,
1580                                         &word_start, &word_end, FALSE);
1581
1582                 if (!empathy_spell_check (str)) {
1583                         gtk_text_buffer_apply_tag_by_name (buffer,
1584                                         "misspelled", &word_start, &word_end);
1585                 } else {
1586                         gtk_text_buffer_remove_tag_by_name (buffer,
1587                                         "misspelled", &word_start, &word_end);
1588                 }
1589
1590                 g_free (str);
1591         }
1592
1593 out:
1594         gtk_text_buffer_move_mark (buffer, mark, &pos);
1595 }
1596
1597 static gboolean
1598 empathy_isspace_cb (gunichar c,
1599                  gpointer data)
1600 {
1601         return g_unichar_isspace (c);
1602 }
1603
1604 static gboolean
1605 chat_input_key_press_event_cb (GtkWidget   *widget,
1606                                GdkEventKey *event,
1607                                EmpathyChat *chat)
1608 {
1609         EmpathyChatPriv *priv;
1610         GtkAdjustment  *adj;
1611         gdouble         val;
1612         GtkWidget      *text_view_sw;
1613
1614         priv = GET_PRIV (chat);
1615
1616         /* Catch ctrl+up/down so we can traverse messages we sent */
1617         if ((event->state & GDK_CONTROL_MASK) &&
1618             (event->keyval == GDK_KEY_Up ||
1619              event->keyval == GDK_KEY_Down)) {
1620                 GtkTextBuffer *buffer;
1621                 const gchar   *str;
1622
1623                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1624                 chat_input_history_update (chat, buffer);
1625
1626                 if (event->keyval == GDK_KEY_Up) {
1627                         str = chat_input_history_get_next (chat);
1628                 } else {
1629                         str = chat_input_history_get_prev (chat);
1630                 }
1631
1632                 g_signal_handlers_block_by_func (buffer,
1633                                                  chat_input_text_buffer_changed_cb,
1634                                                  chat);
1635                 gtk_text_buffer_set_text (buffer, str ? str : "", -1);
1636                 g_signal_handlers_unblock_by_func (buffer,
1637                                                    chat_input_text_buffer_changed_cb,
1638                                                    chat);
1639
1640                 return TRUE;
1641         }
1642
1643         /* Catch enter but not ctrl/shift-enter */
1644         if (IS_ENTER (event->keyval) &&
1645             !(event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
1646                 GtkTextView *view;
1647
1648                 /* This is to make sure that kinput2 gets the enter. And if
1649                  * it's handled there we shouldn't send on it. This is because
1650                  * kinput2 uses Enter to commit letters. See:
1651                  * http://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=104299
1652                  */
1653
1654                 view = GTK_TEXT_VIEW (chat->input_text_view);
1655                 if (gtk_text_view_im_context_filter_keypress (view, event)) {
1656                         gtk_text_view_reset_im_context (view);
1657                         return TRUE;
1658                 }
1659
1660                 chat_input_text_view_send (chat);
1661                 return TRUE;
1662         }
1663
1664         text_view_sw = gtk_widget_get_parent (GTK_WIDGET (chat->view));
1665
1666         if (IS_ENTER (event->keyval) &&
1667             (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
1668                 /* Newline for shift/control-enter. */
1669                 return FALSE;
1670         }
1671         if (!(event->state & GDK_CONTROL_MASK) &&
1672             event->keyval == GDK_KEY_Page_Up) {
1673                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
1674                 gtk_adjustment_set_value (adj, gtk_adjustment_get_value (adj) - gtk_adjustment_get_page_size (adj));
1675                 return TRUE;
1676         }
1677         if ((event->state & GDK_CONTROL_MASK) != GDK_CONTROL_MASK &&
1678             event->keyval == GDK_KEY_Page_Down) {
1679                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
1680                 val = MIN (gtk_adjustment_get_value (adj) + gtk_adjustment_get_page_size (adj),
1681                            gtk_adjustment_get_upper (adj) - gtk_adjustment_get_page_size (adj));
1682                 gtk_adjustment_set_value (adj, val);
1683                 return TRUE;
1684         }
1685         if (event->keyval == GDK_KEY_Escape) {
1686                 empathy_search_bar_hide (EMPATHY_SEARCH_BAR (priv->search_bar));
1687         }
1688         if (!(event->state & (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) &&
1689             event->keyval == GDK_KEY_Tab) {
1690                 GtkTextBuffer *buffer;
1691                 GtkTextIter    start, current;
1692                 gchar         *nick, *completed;
1693                 GList         *list, *completed_list;
1694                 gboolean       is_start_of_buffer;
1695
1696                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (EMPATHY_CHAT (chat)->input_text_view));
1697                 gtk_text_buffer_get_iter_at_mark (buffer, &current, gtk_text_buffer_get_insert (buffer));
1698
1699                 /* Get the start of the nick to complete. */
1700                 gtk_text_buffer_get_iter_at_mark (buffer, &start, gtk_text_buffer_get_insert (buffer));
1701                 if (gtk_text_iter_backward_find_char (&start, &empathy_isspace_cb, NULL, NULL)) {
1702                         gtk_text_iter_set_offset (&start, gtk_text_iter_get_offset (&start) + 1);
1703                 }
1704                 is_start_of_buffer = gtk_text_iter_is_start (&start);
1705
1706                 list = empathy_contact_list_get_members (EMPATHY_CONTACT_LIST (priv->tp_chat));
1707                 g_completion_add_items (priv->completion, list);
1708
1709                 nick = gtk_text_buffer_get_text (buffer, &start, &current, FALSE);
1710                 completed_list = g_completion_complete (priv->completion,
1711                                                         nick,
1712                                                         &completed);
1713
1714                 g_free (nick);
1715
1716                 if (completed) {
1717                         guint        len;
1718                         const gchar *text;
1719                         GString     *message = NULL;
1720                         GList       *l;
1721
1722                         gtk_text_buffer_delete (buffer, &start, &current);
1723
1724                         len = g_list_length (completed_list);
1725
1726                         if (len == 1) {
1727                                 /* If we only have one hit, use that text
1728                                  * instead of the text in completed since the
1729                                  * completed text will use the typed string
1730                                  * which might be cased all wrong.
1731                                  * Fixes #120876
1732                                  * */
1733                                 text = empathy_contact_get_alias (completed_list->data);
1734                         } else {
1735                                 text = completed;
1736
1737                                 /* Print all hits to the scrollback view, so the
1738                                  * user knows what possibilities he has.
1739                                  * Fixes #599779
1740                                  * */
1741                                  message = g_string_new ("");
1742                                  for (l = completed_list; l != NULL; l = l->next) {
1743                                         g_string_append (message, empathy_contact_get_alias (l->data));
1744                                         g_string_append (message, " - ");
1745                                  }
1746                                  empathy_chat_view_append_event (chat->view, message->str);
1747                                  g_string_free (message, TRUE);
1748                         }
1749
1750                         gtk_text_buffer_insert_at_cursor (buffer, text, strlen (text));
1751
1752                         if (len == 1 && is_start_of_buffer) {
1753                             gchar *complete_char;
1754
1755                             complete_char = g_settings_get_string (
1756                                     priv->gsettings_chat,
1757                                     EMPATHY_PREFS_CHAT_NICK_COMPLETION_CHAR);
1758
1759                             if (complete_char != NULL) {
1760                                 gtk_text_buffer_insert_at_cursor (buffer,
1761                                                                   complete_char,
1762                                                                   strlen (complete_char));
1763                                 gtk_text_buffer_insert_at_cursor (buffer, " ", 1);
1764                                 g_free (complete_char);
1765                             }
1766                         }
1767
1768                         g_free (completed);
1769                 }
1770
1771                 g_completion_clear_items (priv->completion);
1772
1773                 g_list_foreach (list, (GFunc) g_object_unref, NULL);
1774                 g_list_free (list);
1775
1776                 return TRUE;
1777         }
1778
1779         return FALSE;
1780 }
1781
1782 static gboolean
1783 chat_text_view_focus_in_event_cb (GtkWidget  *widget,
1784                                   GdkEvent   *event,
1785                                   EmpathyChat *chat)
1786 {
1787         gtk_widget_grab_focus (chat->input_text_view);
1788
1789         return TRUE;
1790 }
1791
1792 static void
1793 chat_input_realize_cb (GtkWidget   *widget,
1794                        EmpathyChat *chat)
1795 {
1796         DEBUG ("Setting focus to the input text view");
1797         if (gtk_widget_is_sensitive (widget)) {
1798                 gtk_widget_grab_focus (widget);
1799         }
1800 }
1801
1802 static void
1803 chat_input_has_focus_notify_cb (GtkWidget   *widget,
1804                                 GParamSpec  *pspec,
1805                                 EmpathyChat *chat)
1806 {
1807         empathy_chat_view_focus_toggled (chat->view, gtk_widget_has_focus (widget));
1808 }
1809
1810 static void
1811 chat_insert_smiley_activate_cb (EmpathySmileyManager *manager,
1812                                 EmpathySmiley        *smiley,
1813                                 gpointer              user_data)
1814 {
1815         EmpathyChat   *chat = EMPATHY_CHAT (user_data);
1816         GtkTextBuffer *buffer;
1817         GtkTextIter    iter;
1818
1819         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1820
1821         gtk_text_buffer_get_end_iter (buffer, &iter);
1822         gtk_text_buffer_insert (buffer, &iter, smiley->str, -1);
1823
1824         gtk_text_buffer_get_end_iter (buffer, &iter);
1825         gtk_text_buffer_insert (buffer, &iter, " ", -1);
1826 }
1827
1828 typedef struct {
1829         EmpathyChat  *chat;
1830         gchar       *word;
1831
1832         GtkTextIter  start;
1833         GtkTextIter  end;
1834 } EmpathyChatSpell;
1835
1836 static EmpathyChatSpell *
1837 chat_spell_new (EmpathyChat  *chat,
1838                 const gchar *word,
1839                 GtkTextIter  start,
1840                 GtkTextIter  end)
1841 {
1842         EmpathyChatSpell *chat_spell;
1843
1844         chat_spell = g_slice_new0 (EmpathyChatSpell);
1845
1846         chat_spell->chat = g_object_ref (chat);
1847         chat_spell->word = g_strdup (word);
1848         chat_spell->start = start;
1849         chat_spell->end = end;
1850
1851         return chat_spell;
1852 }
1853
1854 static void
1855 chat_spell_free (EmpathyChatSpell *chat_spell)
1856 {
1857         g_object_unref (chat_spell->chat);
1858         g_free (chat_spell->word);
1859         g_slice_free (EmpathyChatSpell, chat_spell);
1860 }
1861
1862 static void
1863 chat_spelling_menu_activate_cb (GtkMenuItem     *menu_item,
1864                                                 EmpathyChatSpell *chat_spell)
1865 {
1866     empathy_chat_correct_word (chat_spell->chat,
1867                                &(chat_spell->start),
1868                                &(chat_spell->end),
1869                                gtk_menu_item_get_label (menu_item));
1870 }
1871
1872
1873 static GtkWidget *
1874 chat_spelling_build_suggestions_menu (const gchar *code,
1875                                       EmpathyChatSpell *chat_spell)
1876 {
1877         GList     *suggestions, *l;
1878         GtkWidget *menu, *menu_item;
1879
1880         suggestions = empathy_spell_get_suggestions (code, chat_spell->word);
1881         if (suggestions == NULL)
1882                 return NULL;
1883
1884         menu = gtk_menu_new ();
1885         for (l = suggestions; l; l = l->next) {
1886                 menu_item = gtk_menu_item_new_with_label (l->data);
1887                 g_signal_connect (G_OBJECT (menu_item), "activate",
1888                                   G_CALLBACK (chat_spelling_menu_activate_cb),
1889                                   chat_spell);
1890                 gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
1891         }
1892         empathy_spell_free_suggestions (suggestions);
1893
1894         gtk_widget_show_all (menu);
1895
1896         return menu;
1897 }
1898
1899 static GtkWidget *
1900 chat_spelling_build_menu (EmpathyChatSpell *chat_spell)
1901 {
1902         GtkWidget *menu, *submenu, *item;
1903         GList     *codes, *l;
1904
1905         codes = empathy_spell_get_enabled_language_codes ();
1906         g_assert (codes != NULL);
1907
1908         if (g_list_length (codes) > 1) {
1909                 menu = gtk_menu_new ();
1910
1911                 for (l = codes; l; l = l->next) {
1912                         const gchar *code, *name;
1913
1914                         code = l->data;
1915                         name = empathy_spell_get_language_name (code);
1916                         if (!name)
1917                                 continue;
1918
1919                         item = gtk_image_menu_item_new_with_label (name);
1920
1921                         submenu = chat_spelling_build_suggestions_menu (
1922                                         code, chat_spell);
1923                         if (submenu == NULL)
1924                                 gtk_widget_set_sensitive (item, FALSE);
1925                         else
1926                                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item),
1927                                                            submenu);
1928                         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1929                 }
1930         } else {
1931                 menu = chat_spelling_build_suggestions_menu (codes->data,
1932                                                              chat_spell);
1933                 if (menu == NULL) {
1934                         menu = gtk_menu_new ();
1935                         item = gtk_menu_item_new_with_label (_("(No Suggestions)"));
1936                         gtk_widget_set_sensitive (item, FALSE);
1937                         gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
1938                 }
1939         }
1940         g_list_free (codes);
1941
1942         gtk_widget_show_all (menu);
1943
1944         return menu;
1945 }
1946
1947 typedef struct {
1948         EmpathyChat  *chat;
1949         gchar        *word;
1950         gchar        *code;
1951 } EmpathyChatWord;
1952
1953 static EmpathyChatWord *
1954 chat_word_new (EmpathyChat  *chat,
1955                 const gchar  *word,
1956                 const gchar  *code)
1957 {
1958         EmpathyChatWord *chat_word;
1959
1960         chat_word = g_slice_new0 (EmpathyChatWord);
1961
1962         chat_word->chat = g_object_ref (chat);
1963         chat_word->word = g_strdup (word);
1964         chat_word->code = g_strdup (code);
1965
1966         return chat_word;
1967 }
1968
1969 static void
1970 chat_word_free (EmpathyChatWord *chat_word)
1971 {
1972         g_object_unref (chat_word->chat);
1973         g_free (chat_word->word);
1974         g_free (chat_word->code);
1975         g_slice_free (EmpathyChatWord, chat_word);
1976 }
1977
1978 static void
1979 chat_add_to_dictionary_activate_cb (GtkMenuItem     *menu_item,
1980                                     EmpathyChatWord *chat_word)
1981 {
1982         EmpathyChatPriv *priv = GET_PRIV (chat_word->chat);
1983
1984         empathy_spell_add_to_dictionary (chat_word->code,
1985                                          chat_word->word);
1986         priv->update_misspelled_words_id =
1987                 g_idle_add (update_misspelled_words, chat_word->chat);
1988 }
1989
1990 static GtkWidget *
1991 chat_spelling_build_add_to_dictionary_item (EmpathyChatSpell *chat_spell)
1992 {
1993         GtkWidget       *menu, *item, *lang_item, *image;
1994         GList           *codes, *l;
1995         gchar           *label;
1996         const gchar     *code, *name;
1997         EmpathyChatWord *chat_word;
1998
1999         codes = empathy_spell_get_enabled_language_codes ();
2000         g_assert (codes != NULL);
2001         if (g_list_length (codes) > 1) {
2002                 /* translators: %s is the selected word */
2003                 label = g_strdup_printf (_("Add '%s' to Dictionary"),
2004                                         chat_spell->word);
2005                 item = gtk_image_menu_item_new_with_mnemonic (label);
2006                 g_free (label);
2007                 image = gtk_image_new_from_icon_name (GTK_STOCK_ADD,
2008                                                       GTK_ICON_SIZE_MENU);
2009                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item),
2010                                                image);
2011
2012                 menu = gtk_menu_new ();
2013
2014                 for (l = codes; l; l = l->next) {
2015                         code = l->data;
2016                         name = empathy_spell_get_language_name (code);
2017                         if (name == NULL)
2018                                 continue;
2019
2020                         lang_item = gtk_image_menu_item_new_with_label (name);
2021
2022                         chat_word= chat_word_new (chat_spell->chat,
2023                                                   chat_spell->word, code);
2024                         g_object_set_data_full (G_OBJECT (lang_item),
2025                                 "chat-word", chat_word,
2026                                 (GDestroyNotify) chat_word_free);
2027
2028                         g_signal_connect (G_OBJECT (lang_item), "activate",
2029                                 G_CALLBACK (chat_add_to_dictionary_activate_cb),
2030                                 chat_word);
2031                         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), lang_item);
2032                 }
2033                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), menu);
2034         } else {
2035                 code = codes->data;
2036                 name = empathy_spell_get_language_name (code);
2037                 g_assert (name != NULL);
2038                 /* translators: first %s is the selected word,
2039                  * second %s is the language name of the target dictionary */
2040                 label = g_strdup_printf (_("Add '%s' to %s Dictionary"),
2041                                         chat_spell->word, name);
2042                 item = gtk_image_menu_item_new_with_mnemonic (label);
2043                 g_free (label);
2044                 image = gtk_image_new_from_icon_name (GTK_STOCK_ADD,
2045                                                       GTK_ICON_SIZE_MENU);
2046                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
2047
2048                 chat_word = chat_word_new (chat_spell->chat, chat_spell->word,
2049                                            code);
2050                 g_object_set_data_full (G_OBJECT (item), "chat-word", chat_word,
2051                                         (GDestroyNotify) chat_word_free);
2052
2053                 g_signal_connect (G_OBJECT (item), "activate",
2054                                   G_CALLBACK (chat_add_to_dictionary_activate_cb),
2055                                   chat_word);
2056         }
2057         g_list_free (codes);
2058
2059         gtk_widget_show_all (item);
2060
2061         return item;
2062 }
2063
2064 static void
2065 chat_text_send_cb (GtkMenuItem *menuitem,
2066                    EmpathyChat *chat)
2067 {
2068         chat_input_text_view_send (chat);
2069 }
2070
2071 static void
2072 chat_input_populate_popup_cb (GtkTextView *view,
2073                               GtkMenu     *menu,
2074                               EmpathyChat *chat)
2075 {
2076         GtkTextBuffer        *buffer;
2077         GtkTextTagTable      *table;
2078         GtkTextTag           *tag;
2079         gint                  x, y;
2080         GtkTextIter           iter, start, end;
2081         GtkWidget            *item;
2082         gchar                *str = NULL;
2083         EmpathyChatSpell     *chat_spell;
2084         GtkWidget            *spell_menu;
2085         GtkWidget            *spell_item;
2086         EmpathySmileyManager *smiley_manager;
2087         GtkWidget            *smiley_menu;
2088         GtkWidget            *image;
2089
2090         buffer = gtk_text_view_get_buffer (view);
2091
2092         /* Add the emoticon menu. */
2093         item = gtk_separator_menu_item_new ();
2094         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2095         gtk_widget_show (item);
2096
2097         item = gtk_image_menu_item_new_with_mnemonic (_("Insert Smiley"));
2098         image = gtk_image_new_from_icon_name ("face-smile",
2099                                               GTK_ICON_SIZE_MENU);
2100         gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
2101         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2102         gtk_widget_show (item);
2103
2104         smiley_manager = empathy_smiley_manager_dup_singleton ();
2105         smiley_menu = empathy_smiley_menu_new (smiley_manager,
2106                                                chat_insert_smiley_activate_cb,
2107                                                chat);
2108         gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), smiley_menu);
2109         g_object_unref (smiley_manager);
2110
2111         /* Add the Send menu item. */
2112         gtk_text_buffer_get_bounds (buffer, &start, &end);
2113         str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
2114         if (!EMP_STR_EMPTY (str)) {
2115                 item = gtk_menu_item_new_with_mnemonic (_("_Send"));
2116                 g_signal_connect (G_OBJECT (item), "activate",
2117                                   G_CALLBACK (chat_text_send_cb), chat);
2118                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2119                 gtk_widget_show (item);
2120         }
2121         str = NULL;
2122
2123         /* Add the spell check menu item. */
2124         table = gtk_text_buffer_get_tag_table (buffer);
2125         tag = gtk_text_tag_table_lookup (table, "misspelled");
2126         gtk_widget_get_pointer (GTK_WIDGET (view), &x, &y);
2127         gtk_text_view_window_to_buffer_coords (GTK_TEXT_VIEW (view),
2128                                                GTK_TEXT_WINDOW_WIDGET,
2129                                                x, y,
2130                                                &x, &y);
2131         gtk_text_view_get_iter_at_location (GTK_TEXT_VIEW (view), &iter, x, y);
2132         start = end = iter;
2133         if (gtk_text_iter_backward_to_tag_toggle (&start, tag) &&
2134             gtk_text_iter_forward_to_tag_toggle (&end, tag)) {
2135
2136                 str = gtk_text_buffer_get_text (buffer,
2137                                                 &start, &end, FALSE);
2138         }
2139         if (!EMP_STR_EMPTY (str)) {
2140                 chat_spell = chat_spell_new (chat, str, start, end);
2141                 g_object_set_data_full (G_OBJECT (menu),
2142                                         "chat-spell", chat_spell,
2143                                         (GDestroyNotify) chat_spell_free);
2144
2145                 item = gtk_separator_menu_item_new ();
2146                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2147                 gtk_widget_show (item);
2148
2149                 /* Spelling suggestions */
2150                 item = gtk_image_menu_item_new_with_mnemonic (_("_Spelling Suggestions"));
2151                 image = gtk_image_new_from_icon_name (GTK_STOCK_SPELL_CHECK,
2152                                                       GTK_ICON_SIZE_MENU);
2153                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
2154
2155                 spell_menu = chat_spelling_build_menu (chat_spell);
2156                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), spell_menu);
2157
2158
2159                 spell_item = gtk_separator_menu_item_new ();
2160                 gtk_menu_shell_append (GTK_MENU_SHELL (spell_menu), spell_item);
2161                 gtk_widget_show (spell_item);
2162
2163                 /* Add to dictionary */
2164                 spell_item = chat_spelling_build_add_to_dictionary_item (chat_spell);
2165
2166                 gtk_menu_shell_append (GTK_MENU_SHELL (spell_menu), spell_item);
2167                 gtk_widget_show (spell_item);
2168
2169                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2170                 gtk_widget_show (item);
2171         }
2172 }
2173
2174
2175 static gboolean
2176 chat_log_filter (TplEvent *log,
2177                  gpointer user_data)
2178 {
2179         EmpathyChat *chat = user_data;
2180         EmpathyMessage *message;
2181         EmpathyChatPriv *priv = GET_PRIV (chat);
2182         const GList *pending;
2183
2184         g_return_val_if_fail (TPL_IS_EVENT (log), FALSE);
2185         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
2186
2187         pending = empathy_tp_chat_get_pending_messages (priv->tp_chat);
2188         message = empathy_message_from_tpl_log_event (log);
2189
2190         for (; pending; pending = g_list_next (pending)) {
2191                 if (empathy_message_equal (message, pending->data)) {
2192                         g_object_unref (message);
2193                         return FALSE;
2194                 }
2195         }
2196
2197         g_object_unref (message);
2198         return TRUE;
2199 }
2200
2201
2202 static void
2203 show_pending_messages (EmpathyChat *chat) {
2204         EmpathyChatPriv *priv = GET_PRIV (chat);
2205         const GList *messages, *l;
2206
2207         g_return_if_fail (EMPATHY_IS_CHAT (chat));
2208
2209         if (chat->view == NULL || priv->tp_chat == NULL)
2210                 return;
2211
2212         if (!priv->can_show_pending)
2213                 return;
2214
2215         messages = empathy_tp_chat_get_pending_messages (priv->tp_chat);
2216
2217         for (l = messages; l != NULL ; l = g_list_next (l)) {
2218                 EmpathyMessage *message = EMPATHY_MESSAGE (l->data);
2219                 chat_message_received (chat, message, TRUE);
2220         }
2221 }
2222
2223
2224 static void
2225 got_filtered_messages_cb (GObject *manager,
2226                 GAsyncResult *result,
2227                 gpointer user_data)
2228 {
2229         GList *l;
2230         GList *messages;
2231         EmpathyChat *chat = EMPATHY_CHAT (user_data);
2232         EmpathyChatPriv *priv = GET_PRIV (chat);
2233         GError *error = NULL;
2234
2235         if (!tpl_log_manager_get_filtered_events_finish (TPL_LOG_MANAGER (manager),
2236                 result, &messages, &error)) {
2237                 DEBUG ("%s. Aborting.", error->message);
2238                 empathy_chat_view_append_event (chat->view,
2239                         _("Failed to retrieve recent logs"));
2240                 g_error_free (error);
2241                 goto out;
2242         }
2243
2244         for (l = messages; l; l = g_list_next (l)) {
2245                 EmpathyMessage *message;
2246                 g_assert (TPL_IS_EVENT (l->data));
2247
2248                 message = empathy_message_from_tpl_log_event (l->data);
2249                 g_object_unref (l->data);
2250
2251                 empathy_chat_view_append_message (chat->view, message);
2252                 g_object_unref (message);
2253         }
2254         g_list_free (messages);
2255
2256 out:
2257         /* in case of TPL error, skip backlog and show pending messages */
2258         priv->can_show_pending = TRUE;
2259         show_pending_messages (chat);
2260
2261         /* FIXME: See Bug#610994, we are forcing the ACK of the queue. See comments
2262          * about it in EmpathyChatPriv definition */
2263         priv->retrieving_backlogs = FALSE;
2264         empathy_chat_messages_read (chat);
2265
2266         /* Turn back on scrolling */
2267         empathy_chat_view_scroll (chat->view, TRUE);
2268 }
2269
2270 static void
2271 chat_add_logs (EmpathyChat *chat)
2272 {
2273         EmpathyChatPriv *priv = GET_PRIV (chat);
2274         TplEntity       *target;
2275
2276         if (!priv->id) {
2277                 return;
2278         }
2279
2280         /* Turn off scrolling temporarily */
2281         empathy_chat_view_scroll (chat->view, FALSE);
2282
2283         /* Add messages from last conversation */
2284         if (priv->handle_type == TP_HANDLE_TYPE_ROOM)
2285           target = tpl_entity_new_from_room_id (priv->id);
2286         else
2287           target = tpl_entity_new (priv->id, TPL_ENTITY_CONTACT, NULL, NULL);
2288
2289         priv->retrieving_backlogs = TRUE;
2290         tpl_log_manager_get_filtered_events_async (priv->log_manager,
2291                                                    priv->account,
2292                                                    target,
2293                                                    TPL_EVENT_MASK_TEXT,
2294                                                    5,
2295                                                    chat_log_filter,
2296                                                    chat,
2297                                                    got_filtered_messages_cb,
2298                                                    (gpointer) chat);
2299
2300         g_object_unref (target);
2301 }
2302
2303 static gint
2304 chat_contacts_completion_func (const gchar *s1,
2305                                const gchar *s2,
2306                                gsize        n)
2307 {
2308         gchar *tmp, *nick1, *nick2;
2309         gint   ret;
2310
2311         if (s1 == s2) {
2312                 return 0;
2313         }
2314         if (!s1 || !s2) {
2315                 return s1 ? -1 : +1;
2316         }
2317
2318         tmp = g_utf8_normalize (s1, -1, G_NORMALIZE_DEFAULT);
2319         nick1 = g_utf8_casefold (tmp, -1);
2320         g_free (tmp);
2321
2322         tmp = g_utf8_normalize (s2, -1, G_NORMALIZE_DEFAULT);
2323         nick2 = g_utf8_casefold (tmp, -1);
2324         g_free (tmp);
2325
2326         ret = strncmp (nick1, nick2, n);
2327
2328         g_free (nick1);
2329         g_free (nick2);
2330
2331         return ret;
2332 }
2333
2334 static gchar *
2335 build_part_message (guint           reason,
2336                     const gchar    *name,
2337                     EmpathyContact *actor,
2338                     const gchar    *message)
2339 {
2340         GString *s = g_string_new ("");
2341         const gchar *actor_name = NULL;
2342
2343         if (actor != NULL) {
2344                 actor_name = empathy_contact_get_alias (actor);
2345         }
2346
2347         /* Having an actor only really makes sense for a few actions... */
2348         switch (reason) {
2349         case TP_CHANNEL_GROUP_CHANGE_REASON_OFFLINE:
2350                 g_string_append_printf (s, _("%s has disconnected"), name);
2351                 break;
2352         case TP_CHANNEL_GROUP_CHANGE_REASON_KICKED:
2353                 if (actor_name != NULL) {
2354                         /* translators: reverse the order of these arguments
2355                          * if the kicked should come before the kicker in your locale.
2356                          */
2357                         g_string_append_printf (s, _("%1$s was kicked by %2$s"),
2358                                 name, actor_name);
2359                 } else {
2360                         g_string_append_printf (s, _("%s was kicked"), name);
2361                 }
2362                 break;
2363         case TP_CHANNEL_GROUP_CHANGE_REASON_BANNED:
2364                 if (actor_name != NULL) {
2365                         /* translators: reverse the order of these arguments
2366                          * if the banned should come before the banner in your locale.
2367                          */
2368                         g_string_append_printf (s, _("%1$s was banned by %2$s"),
2369                                 name, actor_name);
2370                 } else {
2371                         g_string_append_printf (s, _("%s was banned"), name);
2372                 }
2373                 break;
2374         default:
2375                 g_string_append_printf (s, _("%s has left the room"), name);
2376         }
2377
2378         if (!EMP_STR_EMPTY (message)) {
2379                 /* Note to translators: this string is appended to
2380                  * notifications like "foo has left the room", with the message
2381                  * given by the user living the room. If this poses a problem,
2382                  * please let us know. :-)
2383                  */
2384                 g_string_append_printf (s, _(" (%s)"), message);
2385         }
2386
2387         return g_string_free (s, FALSE);
2388 }
2389
2390 static void
2391 chat_members_changed_cb (EmpathyTpChat  *tp_chat,
2392                          EmpathyContact *contact,
2393                          EmpathyContact *actor,
2394                          guint           reason,
2395                          gchar          *message,
2396                          gboolean        is_member,
2397                          EmpathyChat    *chat)
2398 {
2399         EmpathyChatPriv *priv = GET_PRIV (chat);
2400         const gchar *name = empathy_contact_get_alias (contact);
2401         gchar *str;
2402
2403         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED != reason);
2404
2405         if (priv->block_events_timeout_id != 0)
2406                 return;
2407
2408         if (is_member) {
2409                 str = g_strdup_printf (_("%s has joined the room"),
2410                                        name);
2411         } else {
2412                 str = build_part_message (reason, name, actor, message);
2413         }
2414
2415         empathy_chat_view_append_event (chat->view, str);
2416         g_free (str);
2417 }
2418
2419 static void
2420 chat_member_renamed_cb (EmpathyTpChat  *tp_chat,
2421                          EmpathyContact *old_contact,
2422                          EmpathyContact *new_contact,
2423                          guint           reason,
2424                          gchar          *message,
2425                          EmpathyChat    *chat)
2426 {
2427         EmpathyChatPriv *priv = GET_PRIV (chat);
2428
2429         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED == reason);
2430
2431         if (priv->block_events_timeout_id == 0) {
2432                 gchar *str;
2433
2434                 str = g_strdup_printf (_("%s is now known as %s"),
2435                                        empathy_contact_get_alias (old_contact),
2436                                        empathy_contact_get_alias (new_contact));
2437                 empathy_chat_view_append_event (chat->view, str);
2438                 g_free (str);
2439         }
2440
2441 }
2442
2443 static gboolean
2444 chat_reset_size_request (gpointer widget)
2445 {
2446         gtk_widget_set_size_request (widget, -1, -1);
2447
2448         return FALSE;
2449 }
2450
2451 static void
2452 chat_update_contacts_visibility (EmpathyChat *chat,
2453                          gboolean show)
2454 {
2455         EmpathyChatPriv *priv = GET_PRIV (chat);
2456         GtkAllocation allocation;
2457
2458         if (!priv->scrolled_window_contacts) {
2459                 return;
2460         }
2461
2462         if (priv->remote_contact != NULL) {
2463                 show = FALSE;
2464         }
2465
2466         if (show && priv->contact_list_view == NULL) {
2467                 EmpathyContactListStore *store;
2468                 gint                     min_width;
2469
2470                 /* We are adding the contact list to the chat, we don't want the
2471                  * chat view to become too small. If the chat view is already
2472                  * smaller than 250 make sure that size won't change. If the
2473                  * chat view is bigger the contact list will take some space on
2474                  * it but we make sure the chat view don't become smaller than
2475                  * 250. Relax the size request once the resize is done */
2476                 gtk_widget_get_allocation (priv->vbox_left, &allocation);
2477                 min_width = MIN (allocation.width, 250);
2478                 gtk_widget_set_size_request (priv->vbox_left, min_width, -1);
2479                 g_idle_add (chat_reset_size_request, priv->vbox_left);
2480
2481                 if (priv->contacts_width > 0) {
2482                         gtk_paned_set_position (GTK_PANED (priv->hpaned),
2483                                                 priv->contacts_width);
2484                 }
2485
2486                 store = empathy_contact_list_store_new (
2487                                 EMPATHY_CONTACT_LIST (priv->tp_chat));
2488                 empathy_contact_list_store_set_show_groups (
2489                                 EMPATHY_CONTACT_LIST_STORE (store), FALSE);
2490
2491                 priv->contact_list_view = GTK_WIDGET (empathy_contact_list_view_new (store,
2492                         EMPATHY_CONTACT_LIST_FEATURE_CONTACT_TOOLTIP,
2493                         EMPATHY_CONTACT_FEATURE_CHAT |
2494                         EMPATHY_CONTACT_FEATURE_CALL |
2495                         EMPATHY_CONTACT_FEATURE_LOG |
2496                         EMPATHY_CONTACT_FEATURE_INFO));
2497                 gtk_container_add (GTK_CONTAINER (priv->scrolled_window_contacts),
2498                                    priv->contact_list_view);
2499                 gtk_widget_show (priv->contact_list_view);
2500                 gtk_widget_show (priv->scrolled_window_contacts);
2501                 g_object_unref (store);
2502         } else if (!show) {
2503                 priv->contacts_width = gtk_paned_get_position (GTK_PANED (priv->hpaned));
2504                 gtk_widget_hide (priv->scrolled_window_contacts);
2505                 if (priv->contact_list_view != NULL) {
2506                         gtk_widget_destroy (priv->contact_list_view);
2507                         priv->contact_list_view = NULL;
2508                 }
2509         }
2510 }
2511
2512 void
2513 empathy_chat_set_show_contacts (EmpathyChat *chat,
2514                                 gboolean     show)
2515 {
2516         EmpathyChatPriv *priv = GET_PRIV (chat);
2517
2518         priv->show_contacts = show;
2519
2520         chat_update_contacts_visibility (chat, show);
2521
2522         g_object_notify (G_OBJECT (chat), "show-contacts");
2523 }
2524
2525 static void
2526 chat_remote_contact_changed_cb (EmpathyChat *chat)
2527 {
2528         EmpathyChatPriv *priv = GET_PRIV (chat);
2529
2530         if (priv->remote_contact != NULL) {
2531                 g_object_unref (priv->remote_contact);
2532                 priv->remote_contact = NULL;
2533         }
2534
2535         g_free (priv->id);
2536
2537         priv->id = g_strdup (empathy_tp_chat_get_id (priv->tp_chat));
2538         priv->remote_contact = empathy_tp_chat_get_remote_contact (priv->tp_chat);
2539         if (priv->remote_contact != NULL) {
2540                 g_object_ref (priv->remote_contact);
2541                 priv->handle_type = TP_HANDLE_TYPE_CONTACT;
2542         }
2543         else if (priv->tp_chat != NULL) {
2544                 TpChannel *channel;
2545
2546                 channel = empathy_tp_chat_get_channel (priv->tp_chat);
2547                 g_object_get (channel, "handle-type", &priv->handle_type, NULL);
2548         }
2549
2550         chat_update_contacts_visibility (chat, priv->show_contacts);
2551
2552         g_object_notify (G_OBJECT (chat), "remote-contact");
2553         g_object_notify (G_OBJECT (chat), "id");
2554 }
2555
2556 static void
2557 chat_destroy_cb (EmpathyTpChat *tp_chat,
2558                  EmpathyChat   *chat)
2559 {
2560         EmpathyChatPriv *priv;
2561
2562         priv = GET_PRIV (chat);
2563
2564         if (!priv->tp_chat) {
2565                 return;
2566         }
2567
2568         chat_composing_remove_timeout (chat);
2569         g_object_unref (priv->tp_chat);
2570         priv->tp_chat = NULL;
2571         g_object_notify (G_OBJECT (chat), "tp-chat");
2572
2573         empathy_chat_view_append_event (chat->view, _("Disconnected"));
2574         gtk_widget_set_sensitive (chat->input_text_view, FALSE);
2575
2576         chat_update_contacts_visibility (chat, FALSE);
2577 }
2578
2579 static gboolean
2580 update_misspelled_words (gpointer data)
2581 {
2582         EmpathyChat *chat = EMPATHY_CHAT (data);
2583         EmpathyChatPriv *priv = GET_PRIV (chat);
2584         GtkTextBuffer *buffer;
2585         GtkTextIter iter;
2586         gint length;
2587
2588         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2589
2590         gtk_text_buffer_get_end_iter (buffer, &iter);
2591         length = gtk_text_iter_get_offset (&iter);
2592         chat_input_text_buffer_insert_text_cb (buffer, &iter,
2593                                                NULL, length, chat);
2594
2595         priv->update_misspelled_words_id = 0;
2596
2597         return FALSE;
2598 }
2599
2600 static void
2601 conf_spell_checking_cb (GSettings *gsettings_chat,
2602                         const gchar *key,
2603                         gpointer user_data)
2604 {
2605         EmpathyChat *chat = EMPATHY_CHAT (user_data);
2606         EmpathyChatPriv *priv = GET_PRIV (chat);
2607         gboolean spell_checker;
2608         GtkTextBuffer *buffer;
2609
2610         if (strcmp (key, EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED) != 0)
2611                 return;
2612
2613         spell_checker = g_settings_get_boolean (gsettings_chat,
2614                         EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED);
2615
2616         if (!empathy_spell_supported ()) {
2617                 spell_checker = FALSE;
2618         }
2619
2620         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2621
2622         if (spell_checker == priv->spell_checking_enabled) {
2623                 if (spell_checker) {
2624                         /* Possibly changed dictionaries,
2625                          * update misspelled words. Need to do so in idle
2626                          * so the spell checker is updated. */
2627                         priv->update_misspelled_words_id =
2628                                 g_idle_add (update_misspelled_words, chat);
2629                 }
2630
2631                 return;
2632         }
2633
2634         if (spell_checker) {
2635                 GtkTextIter iter;
2636
2637                 priv->notify_cursor_position_id = tp_g_signal_connect_object  (
2638                                 buffer, "notify::cursor-position",
2639                                 G_CALLBACK (chat_input_text_buffer_notify_cursor_position_cb),
2640                                 chat, 0);
2641                 priv->insert_text_id = tp_g_signal_connect_object  (
2642                                 buffer, "insert-text",
2643                                 G_CALLBACK (chat_input_text_buffer_insert_text_cb),
2644                                 chat, G_CONNECT_AFTER);
2645                 priv->delete_range_id = tp_g_signal_connect_object  (
2646                                 buffer, "delete-range",
2647                                 G_CALLBACK (chat_input_text_buffer_delete_range_cb),
2648                                 chat, G_CONNECT_AFTER);
2649
2650                 gtk_text_buffer_create_tag (buffer, "misspelled",
2651                                             "underline", PANGO_UNDERLINE_ERROR,
2652                                             NULL);
2653
2654                 gtk_text_buffer_get_iter_at_mark (buffer, &iter,
2655                                                   gtk_text_buffer_get_insert (buffer));
2656                 gtk_text_buffer_create_mark (buffer, "previous-cursor-position",
2657                                              &iter, TRUE);
2658
2659                 /* Mark misspelled words in the existing buffer.
2660                  * Need to do so in idle so the spell checker is updated. */
2661                 priv->update_misspelled_words_id =
2662                         g_idle_add (update_misspelled_words, chat);
2663         } else {
2664                 GtkTextTagTable *table;
2665                 GtkTextTag *tag;
2666
2667                 g_signal_handler_disconnect (buffer, priv->notify_cursor_position_id);
2668                 priv->notify_cursor_position_id = 0;
2669                 g_signal_handler_disconnect (buffer, priv->insert_text_id);
2670                 priv->insert_text_id = 0;
2671                 g_signal_handler_disconnect (buffer, priv->delete_range_id);
2672                 priv->delete_range_id = 0;
2673
2674                 table = gtk_text_buffer_get_tag_table (buffer);
2675                 tag = gtk_text_tag_table_lookup (table, "misspelled");
2676                 gtk_text_tag_table_remove (table, tag);
2677
2678                 gtk_text_buffer_delete_mark_by_name (buffer,
2679                                                      "previous-cursor-position");
2680         }
2681
2682         priv->spell_checking_enabled = spell_checker;
2683 }
2684
2685 static gboolean
2686 save_paned_pos_timeout (gpointer data)
2687 {
2688         EmpathyChat *self = data;
2689         gint hpaned_pos;
2690
2691         hpaned_pos = gtk_paned_get_position (GTK_PANED (self->priv->hpaned));
2692
2693         g_settings_set_int (self->priv->gsettings_ui,
2694                             EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS,
2695                             hpaned_pos);
2696
2697         return FALSE;
2698 }
2699
2700 static gboolean
2701 chat_hpaned_pos_changed_cb (GtkWidget* hpaned,
2702                 GParamSpec *spec,
2703                 gpointer user_data)
2704 {
2705         EmpathyChat *chat = EMPATHY_CHAT (user_data);
2706
2707         if (chat->priv->save_paned_pos_id != 0)
2708                 g_source_remove (chat->priv->save_paned_pos_id);
2709
2710         chat->priv->save_paned_pos_id = g_timeout_add_seconds (1,
2711                 save_paned_pos_timeout, chat);
2712
2713         return TRUE;
2714 }
2715
2716 static void
2717 chat_create_ui (EmpathyChat *chat)
2718 {
2719         EmpathyChatPriv *priv = GET_PRIV (chat);
2720         GtkBuilder      *gui;
2721         GList           *list = NULL;
2722         gchar           *filename;
2723         GtkTextBuffer   *buffer;
2724         gint              paned_pos;
2725         EmpathyThemeManager *theme_mgr;
2726
2727         filename = empathy_file_lookup ("empathy-chat.ui",
2728                                         "libempathy-gtk");
2729         gui = empathy_builder_get_file (filename,
2730                                         "chat_widget", &priv->widget,
2731                                         "hpaned", &priv->hpaned,
2732                                         "vbox_left", &priv->vbox_left,
2733                                         "scrolled_window_chat", &priv->scrolled_window_chat,
2734                                         "scrolled_window_input", &priv->scrolled_window_input,
2735                                         "hbox_topic", &priv->hbox_topic,
2736                                         "expander_topic", &priv->expander_topic,
2737                                         "label_topic", &priv->label_topic,
2738                                         "scrolled_window_contacts", &priv->scrolled_window_contacts,
2739                                         "info_bar_vbox", &priv->info_bar_vbox,
2740                                         NULL);
2741
2742         empathy_builder_connect (gui, chat,
2743                 "expander_topic", "notify::expanded", chat_topic_expander_activate_cb,
2744                 "label_topic", "size-allocate", chat_topic_label_size_allocate_cb,
2745                 NULL);
2746
2747         g_free (filename);
2748
2749         /* Add message view. */
2750         theme_mgr = empathy_theme_manager_dup_singleton ();
2751         chat->view = empathy_theme_manager_create_view (theme_mgr);
2752         g_object_unref (theme_mgr);
2753         /* If this is a GtkTextView, it's set as a drag destination for text/plain
2754            and other types, even though it's non-editable and doesn't accept any
2755            drags.  This steals drag motion for anything inside the scrollbars,
2756            making drag destinations on chat windows far less useful.
2757          */
2758         gtk_drag_dest_unset (GTK_WIDGET (chat->view));
2759         g_signal_connect (chat->view, "focus_in_event",
2760                           G_CALLBACK (chat_text_view_focus_in_event_cb),
2761                           chat);
2762         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_chat),
2763                            GTK_WIDGET (chat->view));
2764         gtk_widget_show (GTK_WIDGET (chat->view));
2765
2766         /* Add input GtkTextView */
2767         chat->input_text_view = empathy_input_text_view_new ();
2768         g_signal_connect (chat->input_text_view, "notify::has-focus",
2769                           G_CALLBACK (chat_input_has_focus_notify_cb),
2770                           chat);
2771         g_signal_connect (chat->input_text_view, "key-press-event",
2772                           G_CALLBACK (chat_input_key_press_event_cb),
2773                           chat);
2774         g_signal_connect (chat->input_text_view, "realize",
2775                           G_CALLBACK (chat_input_realize_cb),
2776                           chat);
2777         g_signal_connect (chat->input_text_view, "populate-popup",
2778                           G_CALLBACK (chat_input_populate_popup_cb),
2779                           chat);
2780         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2781         tp_g_signal_connect_object  (buffer, "changed",
2782                           G_CALLBACK (chat_input_text_buffer_changed_cb),
2783                           chat, 0);
2784         tp_g_signal_connect_object (priv->gsettings_chat,
2785                         "changed::" EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED,
2786                         G_CALLBACK (conf_spell_checking_cb), chat, 0);
2787         conf_spell_checking_cb (priv->gsettings_chat,
2788                                 EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED, chat);
2789         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_input),
2790                            chat->input_text_view);
2791         gtk_widget_show (chat->input_text_view);
2792
2793         /* Add the (invisible) search bar */
2794         priv->search_bar = empathy_search_bar_new (chat->view);
2795         gtk_box_pack_start (GTK_BOX(priv->vbox_left),
2796                             priv->search_bar,
2797                             FALSE, FALSE, 0);
2798         gtk_box_reorder_child (GTK_BOX(priv->vbox_left), priv->search_bar, 1);
2799
2800         /* Initialy hide the topic, will be shown if not empty */
2801         gtk_widget_hide (priv->hbox_topic);
2802
2803         g_signal_connect (priv->hpaned, "notify::position",
2804                           G_CALLBACK (chat_hpaned_pos_changed_cb),
2805                           chat);
2806
2807         /* Load the paned position */
2808         paned_pos = g_settings_get_int (priv->gsettings_ui,
2809                         EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS);
2810         if (paned_pos != 0)
2811                 gtk_paned_set_position (GTK_PANED(priv->hpaned), paned_pos);
2812
2813         /* Set widget focus order */
2814         list = g_list_append (NULL, priv->search_bar);
2815         list = g_list_append (list, priv->scrolled_window_input);
2816         gtk_container_set_focus_chain (GTK_CONTAINER (priv->vbox_left), list);
2817         g_list_free (list);
2818
2819         list = g_list_append (NULL, priv->vbox_left);
2820         list = g_list_append (list, priv->scrolled_window_contacts);
2821         gtk_container_set_focus_chain (GTK_CONTAINER (priv->hpaned), list);
2822         g_list_free (list);
2823
2824         list = g_list_append (NULL, priv->hpaned);
2825         list = g_list_append (list, priv->hbox_topic);
2826         gtk_container_set_focus_chain (GTK_CONTAINER (priv->widget), list);
2827         g_list_free (list);
2828
2829         /* Add the main widget in the chat widget */
2830         gtk_container_add (GTK_CONTAINER (chat), priv->widget);
2831         g_object_unref (gui);
2832 }
2833
2834 static void
2835 chat_size_allocate (GtkWidget     *widget,
2836                     GtkAllocation *allocation)
2837 {
2838   GtkBin *bin = GTK_BIN (widget);
2839   GtkAllocation child_allocation;
2840   GtkWidget *child;
2841
2842   gtk_widget_set_allocation (widget, allocation);
2843
2844   child = gtk_bin_get_child (bin);
2845
2846   if (child && gtk_widget_get_visible (child))
2847     {
2848       child_allocation.x = allocation->x + gtk_container_get_border_width (GTK_CONTAINER (widget));
2849       child_allocation.y = allocation->y + gtk_container_get_border_width (GTK_CONTAINER (widget));
2850       child_allocation.width = MAX (allocation->width - gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2, 0);
2851       child_allocation.height = MAX (allocation->height - gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2, 0);
2852
2853       gtk_widget_size_allocate (child, &child_allocation);
2854     }
2855 }
2856
2857 static void
2858 chat_finalize (GObject *object)
2859 {
2860         EmpathyChat     *chat;
2861         EmpathyChatPriv *priv;
2862
2863         chat = EMPATHY_CHAT (object);
2864         priv = GET_PRIV (chat);
2865
2866         DEBUG ("Finalized: %p", object);
2867
2868         if (priv->update_misspelled_words_id != 0)
2869                 g_source_remove (priv->update_misspelled_words_id);
2870
2871         if (priv->save_paned_pos_id != 0)
2872                 g_source_remove (priv->save_paned_pos_id);
2873
2874         g_object_unref (priv->gsettings_chat);
2875         g_object_unref (priv->gsettings_ui);
2876
2877         g_list_foreach (priv->input_history, (GFunc) chat_input_history_entry_free, NULL);
2878         g_list_free (priv->input_history);
2879
2880         g_list_foreach (priv->compositors, (GFunc) g_object_unref, NULL);
2881         g_list_free (priv->compositors);
2882
2883         chat_composing_remove_timeout (chat);
2884
2885         g_object_unref (priv->account_manager);
2886         g_object_unref (priv->log_manager);
2887
2888         if (priv->tp_chat) {
2889                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2890                         chat_destroy_cb, chat);
2891                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2892                         chat_message_received_cb, chat);
2893                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2894                         chat_pending_message_removed_cb, chat);
2895                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2896                         chat_send_error_cb, chat);
2897                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2898                         chat_state_changed_cb, chat);
2899                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2900                         chat_property_changed_cb, chat);
2901                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2902                         chat_members_changed_cb, chat);
2903                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2904                         chat_remote_contact_changed_cb, chat);
2905                 empathy_tp_chat_leave (priv->tp_chat, "");
2906                 g_object_unref (priv->tp_chat);
2907         }
2908         if (priv->account) {
2909                 g_object_unref (priv->account);
2910         }
2911         if (priv->remote_contact) {
2912                 g_object_unref (priv->remote_contact);
2913         }
2914
2915         if (priv->block_events_timeout_id) {
2916                 g_source_remove (priv->block_events_timeout_id);
2917         }
2918
2919         g_free (priv->id);
2920         g_free (priv->name);
2921         g_free (priv->subject);
2922         g_completion_free (priv->completion);
2923
2924         G_OBJECT_CLASS (empathy_chat_parent_class)->finalize (object);
2925 }
2926
2927 static void
2928 chat_constructed (GObject *object)
2929 {
2930         EmpathyChat *chat = EMPATHY_CHAT (object);
2931         EmpathyChatPriv *priv = GET_PRIV (chat);
2932
2933         if (priv->handle_type != TP_HANDLE_TYPE_ROOM) {
2934                 /* First display logs from the logger and then display pending messages */
2935                 chat_add_logs (chat);
2936         }
2937          else {
2938                 /* Just display pending messages for rooms */
2939                 priv->can_show_pending = TRUE;
2940                 show_pending_messages (chat);
2941         }
2942 }
2943
2944 static void
2945 empathy_chat_class_init (EmpathyChatClass *klass)
2946 {
2947         GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
2948         GObjectClass   *object_class = G_OBJECT_CLASS (klass);
2949
2950         object_class->finalize = chat_finalize;
2951         object_class->get_property = chat_get_property;
2952         object_class->set_property = chat_set_property;
2953         object_class->constructed = chat_constructed;
2954
2955         widget_class->size_allocate = chat_size_allocate;
2956
2957         g_object_class_install_property (object_class,
2958                                          PROP_TP_CHAT,
2959                                          g_param_spec_object ("tp-chat",
2960                                                               "Empathy tp chat",
2961                                                               "The tp chat object",
2962                                                               EMPATHY_TYPE_TP_CHAT,
2963                                                               G_PARAM_CONSTRUCT |
2964                                                               G_PARAM_READWRITE |
2965                                                               G_PARAM_STATIC_STRINGS));
2966         g_object_class_install_property (object_class,
2967                                          PROP_ACCOUNT,
2968                                          g_param_spec_object ("account",
2969                                                               "Account of the chat",
2970                                                               "The account of the chat",
2971                                                               TP_TYPE_ACCOUNT,
2972                                                               G_PARAM_READABLE |
2973                                                               G_PARAM_STATIC_STRINGS));
2974         g_object_class_install_property (object_class,
2975                                          PROP_ID,
2976                                          g_param_spec_string ("id",
2977                                                               "Chat's id",
2978                                                               "The id of the chat",
2979                                                               NULL,
2980                                                               G_PARAM_READABLE |
2981                                                               G_PARAM_STATIC_STRINGS));
2982         g_object_class_install_property (object_class,
2983                                          PROP_NAME,
2984                                          g_param_spec_string ("name",
2985                                                               "Chat's name",
2986                                                               "The name of the chat",
2987                                                               NULL,
2988                                                               G_PARAM_READABLE |
2989                                                               G_PARAM_STATIC_STRINGS));
2990         g_object_class_install_property (object_class,
2991                                          PROP_SUBJECT,
2992                                          g_param_spec_string ("subject",
2993                                                               "Chat's subject",
2994                                                               "The subject or topic of the chat",
2995                                                               NULL,
2996                                                               G_PARAM_READABLE |
2997                                                               G_PARAM_STATIC_STRINGS));
2998         g_object_class_install_property (object_class,
2999                                          PROP_REMOTE_CONTACT,
3000                                          g_param_spec_object ("remote-contact",
3001                                                               "The remote contact",
3002                                                               "The remote contact is any",
3003                                                               EMPATHY_TYPE_CONTACT,
3004                                                               G_PARAM_READABLE |
3005                                                               G_PARAM_STATIC_STRINGS));
3006         g_object_class_install_property (object_class,
3007                                          PROP_SHOW_CONTACTS,
3008                                          g_param_spec_boolean ("show-contacts",
3009                                                                "Contacts' visibility",
3010                                                                "The visibility of the contacts' list",
3011                                                                TRUE,
3012                                                                G_PARAM_READWRITE |
3013                                                                G_PARAM_STATIC_STRINGS));
3014
3015         g_object_class_install_property (object_class,
3016                                          PROP_SMS_CHANNEL,
3017                                          g_param_spec_boolean ("sms-channel",
3018                                                                "SMS Channel",
3019                                                                "TRUE if this channel is for sending SMSes",
3020                                                                FALSE,
3021                                                                G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
3022
3023         g_object_class_install_property (object_class,
3024                                          PROP_N_MESSAGES_SENDING,
3025                                          g_param_spec_uint ("n-messages-sending",
3026                                                             "Num Messages Sending",
3027                                                             "The number of messages being sent",
3028                                                             0, G_MAXUINT, 0,
3029                                                             G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
3030
3031         g_object_class_install_property (object_class,
3032                                          PROP_NB_UNREAD_MESSAGES,
3033                                          g_param_spec_uint ("nb-unread-messages",
3034                                                             "Num Unread Messages",
3035                                                             "The number of unread messages",
3036                                                             0, G_MAXUINT, 0,
3037                                                             G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
3038
3039         signals[COMPOSING] =
3040                 g_signal_new ("composing",
3041                               G_OBJECT_CLASS_TYPE (object_class),
3042                               G_SIGNAL_RUN_LAST,
3043                               0,
3044                               NULL, NULL,
3045                               g_cclosure_marshal_VOID__BOOLEAN,
3046                               G_TYPE_NONE,
3047                               1, G_TYPE_BOOLEAN);
3048
3049         signals[NEW_MESSAGE] =
3050                 g_signal_new ("new-message",
3051                               G_OBJECT_CLASS_TYPE (object_class),
3052                               G_SIGNAL_RUN_LAST,
3053                               0,
3054                               NULL, NULL,
3055                               _empathy_gtk_marshal_VOID__OBJECT_BOOLEAN,
3056                               G_TYPE_NONE,
3057                               2, EMPATHY_TYPE_MESSAGE, G_TYPE_BOOLEAN);
3058
3059         g_type_class_add_private (object_class, sizeof (EmpathyChatPriv));
3060 }
3061
3062 static gboolean
3063 chat_block_events_timeout_cb (gpointer data)
3064 {
3065         EmpathyChatPriv *priv = GET_PRIV (data);
3066
3067         priv->block_events_timeout_id = 0;
3068
3069         return FALSE;
3070 }
3071
3072 static void
3073 account_manager_prepared_cb (GObject *source_object,
3074                              GAsyncResult *result,
3075                              gpointer user_data)
3076 {
3077         GList *accounts, *l;
3078         TpAccountManager *account_manager = TP_ACCOUNT_MANAGER (source_object);
3079         EmpathyChat *chat = user_data;
3080         GError *error = NULL;
3081
3082         if (!tp_account_manager_prepare_finish (account_manager, result, &error)) {
3083                 DEBUG ("Failed to prepare the account manager: %s", error->message);
3084                 g_error_free (error);
3085                 return;
3086         }
3087
3088         accounts = tp_account_manager_get_valid_accounts (account_manager);
3089
3090         for (l = accounts; l != NULL; l = l->next) {
3091                 TpAccount *account = l->data;
3092                 tp_g_signal_connect_object (account, "status-changed",
3093                                              G_CALLBACK (chat_new_connection_cb),
3094                                              chat, 0);
3095         }
3096
3097         g_list_free (accounts);
3098 }
3099
3100 static void
3101 empathy_chat_init (EmpathyChat *chat)
3102 {
3103         EmpathyChatPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chat,
3104                 EMPATHY_TYPE_CHAT, EmpathyChatPriv);
3105
3106         chat->priv = priv;
3107         priv->log_manager = tpl_log_manager_dup_singleton ();
3108         priv->gsettings_chat = g_settings_new (EMPATHY_PREFS_CHAT_SCHEMA);
3109         priv->gsettings_ui = g_settings_new (EMPATHY_PREFS_UI_SCHEMA);
3110
3111         priv->contacts_width = -1;
3112         priv->input_history = NULL;
3113         priv->input_history_current = NULL;
3114         priv->account_manager = tp_account_manager_dup ();
3115
3116         tp_account_manager_prepare_async (priv->account_manager, NULL,
3117                                           account_manager_prepared_cb, chat);
3118
3119         priv->show_contacts = g_settings_get_boolean (priv->gsettings_chat,
3120                         EMPATHY_PREFS_CHAT_SHOW_CONTACTS_IN_ROOMS);
3121
3122         /* Block events for some time to avoid having "has come online" or
3123          * "joined" messages. */
3124         priv->block_events_timeout_id =
3125                 g_timeout_add_seconds (1, chat_block_events_timeout_cb, chat);
3126
3127         /* Add nick name completion */
3128         priv->completion = g_completion_new ((GCompletionFunc) empathy_contact_get_alias);
3129         g_completion_set_compare (priv->completion, chat_contacts_completion_func);
3130
3131         chat_create_ui (chat);
3132 }
3133
3134 EmpathyChat *
3135 empathy_chat_new (EmpathyTpChat *tp_chat)
3136 {
3137         return g_object_new (EMPATHY_TYPE_CHAT, "tp-chat", tp_chat, NULL);
3138 }
3139
3140 EmpathyTpChat *
3141 empathy_chat_get_tp_chat (EmpathyChat *chat)
3142 {
3143         EmpathyChatPriv *priv = GET_PRIV (chat);
3144
3145         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3146
3147         return priv->tp_chat;
3148 }
3149
3150 typedef struct
3151 {
3152         EmpathyChat *self;
3153         GtkWidget *info_bar;
3154         gulong response_id;
3155         GtkWidget *button;
3156         GtkWidget *label;
3157         GtkWidget *entry;
3158         GtkWidget *spinner;
3159         gchar *password;
3160 } PasswordData;
3161
3162 static void
3163 passwd_remember_button_cb (GtkButton *button,
3164                           PasswordData *data)
3165 {
3166         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3167 }
3168
3169 static void
3170 passwd_not_now_button_cb (GtkButton *button,
3171                           PasswordData *data)
3172 {
3173         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_NO);
3174 }
3175
3176 static void
3177 remember_password_infobar_response_cb (GtkWidget *info_bar,
3178                                        gint response_id,
3179                                        PasswordData *data)
3180 {
3181         EmpathyChatPriv *priv = GET_PRIV (data->self);
3182
3183         if (response_id == GTK_RESPONSE_OK) {
3184                 DEBUG ("Saving room password");
3185                 empathy_keyring_set_room_password_async (priv->account,
3186                                                          empathy_tp_chat_get_id (priv->tp_chat),
3187                                                          data->password,
3188                                                          NULL, NULL);
3189         }
3190
3191         gtk_widget_destroy (info_bar);
3192         g_free (data->password);
3193         g_slice_free (PasswordData, data);
3194 }
3195
3196 static void
3197 chat_prompt_to_save_password (EmpathyChat *self,
3198                               PasswordData *data)
3199 {
3200         GtkWidget *content_area;
3201         GtkWidget *hbox;
3202         GtkWidget *image;
3203         GtkWidget *label;
3204         GtkWidget *alig;
3205         GtkWidget *button;
3206
3207         /* save the password in case it needs to be saved */
3208         data->password = g_strdup (gtk_entry_get_text (GTK_ENTRY (data->entry)));
3209
3210         /* Remove all previous widgets */
3211         content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (data->info_bar));
3212         gtk_container_forall (GTK_CONTAINER (content_area),
3213                               (GtkCallback) gtk_widget_destroy, NULL);
3214         data->button = NULL;
3215         data->label = NULL;
3216         data->entry = NULL;
3217         data->spinner = NULL;
3218
3219         gtk_info_bar_set_message_type (GTK_INFO_BAR (data->info_bar),
3220                                        GTK_MESSAGE_QUESTION);
3221
3222         hbox = gtk_hbox_new (FALSE, 5);
3223         gtk_box_pack_start (GTK_BOX (content_area), hbox, TRUE, TRUE, 0);
3224
3225         /* Add image */
3226         image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_AUTHENTICATION,
3227                                           GTK_ICON_SIZE_DIALOG);
3228         gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
3229
3230         /* Add message */
3231         label = gtk_label_new (_("Would you like to store this password?"));
3232         gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0);
3233
3234         /* Add 'Remember' button */
3235         alig = gtk_alignment_new (0, 0.5, 1, 0);
3236
3237         button = gtk_button_new_with_label (_("Remember"));
3238         gtk_container_add (GTK_CONTAINER (alig), button);
3239         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3240
3241         g_signal_connect (button, "clicked", G_CALLBACK (passwd_remember_button_cb),
3242                           data);
3243
3244         /* Add 'Not now' button */
3245         alig = gtk_alignment_new (0, 0.5, 1, 0);
3246
3247         button = gtk_button_new_with_label (_("Not now"));
3248         gtk_container_add (GTK_CONTAINER (alig), button);
3249         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3250
3251         g_signal_connect (button, "clicked", G_CALLBACK (passwd_not_now_button_cb),
3252                           data);
3253
3254         /* go! */
3255         g_signal_handler_disconnect (data->info_bar, data->response_id);
3256         g_signal_connect (data->info_bar, "response",
3257                           G_CALLBACK (remember_password_infobar_response_cb), data);
3258
3259         gtk_widget_show_all (data->info_bar);
3260 }
3261
3262 static void
3263 provide_password_cb (GObject *tp_chat,
3264                      GAsyncResult *res,
3265                      gpointer user_data)
3266 {
3267         PasswordData *data = user_data;
3268         EmpathyChat *self = data->self;
3269         EmpathyChatPriv *priv = GET_PRIV (self);
3270         GError *error = NULL;
3271
3272         if (!empathy_tp_chat_provide_password_finish (EMPATHY_TP_CHAT (tp_chat), res,
3273                                                       &error)) {
3274                 DEBUG ("error: %s", error->message);
3275                 /* FIXME: what should we do if that's another error? Close the channel?
3276                  * Display the raw D-Bus error to the user isn't very useful */
3277                 if (g_error_matches (error, TP_ERRORS, TP_ERROR_AUTHENTICATION_FAILED)) {
3278                         /* entry */
3279                         gtk_entry_set_text (GTK_ENTRY (data->entry), "");
3280                         gtk_widget_set_sensitive (data->entry, TRUE);
3281                         gtk_widget_grab_focus (data->entry);
3282
3283                         /* info bar */
3284                         gtk_info_bar_set_message_type (
3285                             GTK_INFO_BAR (data->info_bar),
3286                             GTK_MESSAGE_ERROR);
3287
3288                         /* button */
3289                         gtk_widget_set_sensitive (data->button, TRUE);
3290                         gtk_button_set_label (GTK_BUTTON (data->button),
3291                             _("Retry"));
3292
3293                         /* label */
3294                         gtk_label_set_text (GTK_LABEL (data->label),
3295                             _("Wrong password; please try again:"));
3296
3297                         /* spinner */
3298                         gtk_spinner_stop (GTK_SPINNER (data->spinner));
3299                         gtk_widget_hide (data->spinner);
3300                 }
3301                 g_error_free (error);
3302                 return;
3303         }
3304
3305         if (empathy_keyring_is_available ()) {
3306                 /* ask whether they want to save the password */
3307                 chat_prompt_to_save_password (self, data);
3308         } else {
3309                 /* Get rid of the password info bar finally */
3310                 gtk_widget_destroy (data->info_bar);
3311                 g_slice_free (PasswordData, data);
3312         }
3313
3314         /* Room joined */
3315         gtk_widget_set_sensitive (priv->hpaned, TRUE);
3316         gtk_widget_grab_focus (self->input_text_view);
3317 }
3318
3319 static void
3320 password_infobar_response_cb (GtkWidget *info_bar,
3321                               gint response_id,
3322                               PasswordData *data)
3323 {
3324         EmpathyChatPriv *priv = GET_PRIV (data->self);
3325         const gchar *password;
3326
3327         if (response_id != GTK_RESPONSE_OK) {
3328                 gtk_widget_destroy (info_bar);
3329                 g_slice_free (PasswordData, data);
3330                 return;
3331         }
3332
3333         password = gtk_entry_get_text (GTK_ENTRY (data->entry));
3334
3335         empathy_tp_chat_provide_password_async (priv->tp_chat, password,
3336                                                 provide_password_cb, data);
3337
3338         gtk_widget_set_sensitive (data->button, FALSE);
3339         gtk_widget_set_sensitive (data->entry, FALSE);
3340
3341         gtk_spinner_start (GTK_SPINNER (data->spinner));
3342         gtk_widget_show (data->spinner);
3343 }
3344
3345 static void
3346 password_entry_activate_cb (GtkWidget *entry,
3347                           PasswordData *data)
3348 {
3349         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3350 }
3351
3352 static void
3353 passwd_join_button_cb (GtkButton *button,
3354                           PasswordData *data)
3355 {
3356         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3357 }
3358
3359 static void
3360 clear_icon_released_cb (GtkEntry *entry,
3361                         GtkEntryIconPosition icon_pos,
3362                         GdkEvent *event,
3363                         PasswordData *data)
3364 {
3365         gtk_entry_set_text (entry, "");
3366 }
3367
3368 static void
3369 password_entry_changed_cb (GtkEditable *entry,
3370                            PasswordData *data)
3371 {
3372         const gchar *str;
3373
3374         str = gtk_entry_get_text (GTK_ENTRY (entry));
3375
3376         gtk_entry_set_icon_sensitive (GTK_ENTRY (entry),
3377             GTK_ENTRY_ICON_SECONDARY, !EMP_STR_EMPTY (str));
3378 }
3379
3380 static void
3381 display_password_info_bar (EmpathyChat *self)
3382 {
3383         EmpathyChatPriv *priv = GET_PRIV (self);
3384         GtkWidget *info_bar;
3385         GtkWidget *content_area;
3386         GtkWidget *hbox;
3387         GtkWidget *image;
3388         GtkWidget *label;
3389         GtkWidget *entry;
3390         GtkWidget *alig;
3391         GtkWidget *button;
3392         GtkWidget *spinner;
3393         PasswordData *data;
3394
3395         data = g_slice_new0 (PasswordData);
3396
3397         info_bar = gtk_info_bar_new ();
3398         gtk_info_bar_set_message_type (GTK_INFO_BAR (info_bar),
3399             GTK_MESSAGE_QUESTION);
3400
3401         content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (info_bar));
3402
3403         hbox = gtk_hbox_new (FALSE, 5);
3404         gtk_box_pack_start (GTK_BOX (content_area), hbox, TRUE, TRUE, 0);
3405
3406         /* Add image */
3407         image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_AUTHENTICATION,
3408                                           GTK_ICON_SIZE_DIALOG);
3409         gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
3410
3411         /* Add message */
3412         label = gtk_label_new (_("This room is protected by a password:"));
3413         gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);
3414
3415         /* Add password entry */
3416         entry = gtk_entry_new ();
3417         gtk_entry_set_visibility (GTK_ENTRY (entry), FALSE);
3418         gtk_box_pack_start (GTK_BOX (hbox), entry, TRUE, TRUE, 0);
3419
3420         gtk_entry_set_icon_from_stock (GTK_ENTRY (entry),
3421                                        GTK_ENTRY_ICON_SECONDARY, GTK_STOCK_CLEAR);
3422         gtk_entry_set_icon_sensitive (GTK_ENTRY (entry),
3423                                       GTK_ENTRY_ICON_SECONDARY, FALSE);
3424
3425         g_signal_connect (entry, "icon-release",
3426                           G_CALLBACK (clear_icon_released_cb), data);
3427         g_signal_connect (entry, "changed",
3428                           G_CALLBACK (password_entry_changed_cb), data);
3429
3430         g_signal_connect (entry, "activate",
3431                           G_CALLBACK (password_entry_activate_cb), data);
3432
3433         /* Focus the password entry once it's realized */
3434         g_signal_connect (entry, "realize", G_CALLBACK (gtk_widget_grab_focus), NULL);
3435
3436         /* Add 'Join' button */
3437         alig = gtk_alignment_new (0, 0.5, 1, 0);
3438
3439         button = gtk_button_new_with_label (_("Join"));
3440         gtk_container_add (GTK_CONTAINER (alig), button);
3441         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3442
3443         g_signal_connect (button, "clicked", G_CALLBACK (passwd_join_button_cb),
3444                           data);
3445
3446         /* Add spinner */
3447         spinner = gtk_spinner_new ();
3448         gtk_box_pack_end (GTK_BOX (hbox), spinner, FALSE, FALSE, 0);
3449
3450         /* Save some data for messing around with later */
3451         data->self = self;
3452         data->info_bar = info_bar;
3453         data->button = button;
3454         data->label = label;
3455         data->entry = entry;
3456         data->spinner = spinner;
3457
3458         gtk_box_pack_start (GTK_BOX (priv->info_bar_vbox), info_bar,
3459                             TRUE, TRUE, 3);
3460         gtk_widget_show_all (hbox);
3461
3462         data->response_id = g_signal_connect (info_bar, "response",
3463                                               G_CALLBACK (password_infobar_response_cb), data);
3464
3465         gtk_widget_show_all (info_bar);
3466         /* ... but hide the spinner */
3467         gtk_widget_hide (spinner);
3468 }
3469
3470 static void
3471 provide_saved_password_cb (GObject *tp_chat,
3472                            GAsyncResult *res,
3473                            gpointer user_data)
3474 {
3475         EmpathyChat *self = user_data;
3476         EmpathyChatPriv *priv = GET_PRIV (self);
3477         GError *error = NULL;
3478
3479         if (!empathy_tp_chat_provide_password_finish (EMPATHY_TP_CHAT (tp_chat), res,
3480                                                       &error)) {
3481                 DEBUG ("error: %s", error->message);
3482                 /* FIXME: what should we do if that's another error? Close the channel?
3483                  * Display the raw D-Bus error to the user isn't very useful */
3484                 if (g_error_matches (error, TP_ERRORS, TP_ERROR_AUTHENTICATION_FAILED)) {
3485                         display_password_info_bar (self);
3486                         gtk_widget_set_sensitive (priv->hpaned, FALSE);
3487                 }
3488                 g_error_free (error);
3489                 return;
3490         }
3491
3492         /* Room joined */
3493         gtk_widget_set_sensitive (priv->hpaned, TRUE);
3494         gtk_widget_grab_focus (self->input_text_view);
3495 }
3496
3497 static void
3498 chat_room_got_password_cb (GObject *source,
3499                            GAsyncResult *result,
3500                            gpointer user_data)
3501 {
3502         EmpathyChat *self = user_data;
3503         EmpathyChatPriv *priv = GET_PRIV (self);
3504         const gchar *password;
3505         GError *error = NULL;
3506
3507         password = empathy_keyring_get_room_password_finish (priv->account,
3508             result, &error);
3509
3510         if (error != NULL) {
3511                 DEBUG ("Couldn't get room password: %s\n", error->message);
3512                 g_clear_error (&error);
3513
3514                 display_password_info_bar (self);
3515                 gtk_widget_set_sensitive (priv->hpaned, FALSE);
3516                 return;
3517         }
3518
3519         empathy_tp_chat_provide_password_async (priv->tp_chat, password,
3520                                                 provide_saved_password_cb, self);
3521 }
3522
3523 static void
3524 chat_password_needed_changed_cb (EmpathyChat *self)
3525 {
3526         EmpathyChatPriv *priv = GET_PRIV (self);
3527
3528         if (empathy_tp_chat_password_needed (priv->tp_chat)) {
3529                 empathy_keyring_get_room_password_async (priv->account,
3530                                                          empathy_tp_chat_get_id (priv->tp_chat),
3531                                                          chat_room_got_password_cb, self);
3532         }
3533 }
3534
3535 static void
3536 chat_sms_channel_changed_cb (EmpathyChat *self)
3537 {
3538         EmpathyChatPriv *priv = GET_PRIV (self);
3539
3540         priv->sms_channel = empathy_tp_chat_is_sms_channel (priv->tp_chat);
3541         g_object_notify (G_OBJECT (self), "sms-channel");
3542 }
3543
3544 static void
3545 chat_n_messages_sending_changed_cb (EmpathyChat *self)
3546 {
3547         g_object_notify (G_OBJECT (self), "n-messages-sending");
3548 }
3549
3550 void
3551 empathy_chat_set_tp_chat (EmpathyChat   *chat,
3552                           EmpathyTpChat *tp_chat)
3553 {
3554         EmpathyChatPriv *priv = GET_PRIV (chat);
3555         GPtrArray       *properties;
3556
3557         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3558         g_return_if_fail (EMPATHY_IS_TP_CHAT (tp_chat));
3559         g_return_if_fail (empathy_tp_chat_is_ready (tp_chat));
3560
3561         if (priv->tp_chat) {
3562                 return;
3563         }
3564
3565         if (priv->account) {
3566                 g_object_unref (priv->account);
3567         }
3568
3569         priv->tp_chat = g_object_ref (tp_chat);
3570         priv->account = g_object_ref (empathy_tp_chat_get_account (priv->tp_chat));
3571
3572         g_signal_connect (tp_chat, "destroy",
3573                           G_CALLBACK (chat_destroy_cb),
3574                           chat);
3575         g_signal_connect (tp_chat, "message-received",
3576                           G_CALLBACK (chat_message_received_cb),
3577                           chat);
3578         g_signal_connect (tp_chat, "pending-message-removed",
3579                           G_CALLBACK (chat_pending_message_removed_cb),
3580                           chat);
3581         g_signal_connect (tp_chat, "send-error",
3582                           G_CALLBACK (chat_send_error_cb),
3583                           chat);
3584         g_signal_connect (tp_chat, "chat-state-changed",
3585                           G_CALLBACK (chat_state_changed_cb),
3586                           chat);
3587         g_signal_connect (tp_chat, "property-changed",
3588                           G_CALLBACK (chat_property_changed_cb),
3589                           chat);
3590         g_signal_connect (tp_chat, "members-changed",
3591                           G_CALLBACK (chat_members_changed_cb),
3592                           chat);
3593         g_signal_connect (tp_chat, "member-renamed",
3594                           G_CALLBACK (chat_member_renamed_cb),
3595                           chat);
3596         g_signal_connect_swapped (tp_chat, "notify::remote-contact",
3597                                   G_CALLBACK (chat_remote_contact_changed_cb),
3598                                   chat);
3599         g_signal_connect_swapped (tp_chat, "notify::password-needed",
3600                                   G_CALLBACK (chat_password_needed_changed_cb),
3601                                   chat);
3602         g_signal_connect_swapped (tp_chat, "notify::sms-channel",
3603                                   G_CALLBACK (chat_sms_channel_changed_cb),
3604                                   chat);
3605         g_signal_connect_swapped (tp_chat, "notify::n-messages-sending",
3606                                   G_CALLBACK (chat_n_messages_sending_changed_cb),
3607                                   chat);
3608
3609         /* Get initial value of properties */
3610         properties = empathy_tp_chat_get_properties (priv->tp_chat);
3611         if (properties != NULL) {
3612                 guint i;
3613
3614                 for (i = 0; i < properties->len; i++) {
3615                         EmpathyTpChatProperty *property;
3616
3617                         property = g_ptr_array_index (properties, i);
3618                         if (property->value == NULL)
3619                                 continue;
3620
3621                         chat_property_changed_cb (priv->tp_chat,
3622                                                   property->name,
3623                                                   property->value,
3624                                                   chat);
3625                 }
3626         }
3627
3628         chat_sms_channel_changed_cb (chat);
3629         chat_remote_contact_changed_cb (chat);
3630
3631         if (chat->input_text_view) {
3632                 gtk_widget_set_sensitive (chat->input_text_view, TRUE);
3633                 if (priv->block_events_timeout_id == 0) {
3634                         empathy_chat_view_append_event (chat->view, _("Connected"));
3635                 }
3636         }
3637
3638         g_object_notify (G_OBJECT (chat), "tp-chat");
3639         g_object_notify (G_OBJECT (chat), "id");
3640         g_object_notify (G_OBJECT (chat), "account");
3641
3642         /* This is a noop when tp-chat is set at object construction time and causes
3643          * the pending messages to be show when it's set on the object after it has
3644          * been created */
3645         show_pending_messages (chat);
3646
3647         /* check if a password is needed */
3648         chat_password_needed_changed_cb (chat);
3649 }
3650
3651 TpAccount *
3652 empathy_chat_get_account (EmpathyChat *chat)
3653 {
3654         EmpathyChatPriv *priv = GET_PRIV (chat);
3655
3656         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3657
3658         return priv->account;
3659 }
3660
3661 const gchar *
3662 empathy_chat_get_id (EmpathyChat *chat)
3663 {
3664         EmpathyChatPriv *priv = GET_PRIV (chat);
3665
3666         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3667
3668         return priv->id;
3669 }
3670
3671 gchar *
3672 empathy_chat_dup_name (EmpathyChat *chat)
3673 {
3674         EmpathyChatPriv *priv = GET_PRIV (chat);
3675         const gchar *ret;
3676
3677         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3678
3679         ret = priv->name;
3680
3681         if (!ret && priv->remote_contact) {
3682                 ret = empathy_contact_get_alias (priv->remote_contact);
3683         }
3684
3685         if (!ret)
3686                 ret = priv->id;
3687
3688         if (!ret)
3689                 ret = _("Conversation");
3690
3691         if (priv->sms_channel)
3692                 /* Translators: this string is a something like
3693                  * "Escher Cat (SMS)" */
3694                 return g_strdup_printf (_("%s (SMS)"), ret);
3695         else
3696                 return g_strdup (ret);
3697 }
3698
3699 const gchar *
3700 empathy_chat_get_subject (EmpathyChat *chat)
3701 {
3702         EmpathyChatPriv *priv = GET_PRIV (chat);
3703
3704         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3705
3706         return priv->subject;
3707 }
3708
3709 EmpathyContact *
3710 empathy_chat_get_remote_contact (EmpathyChat *chat)
3711 {
3712         EmpathyChatPriv *priv = GET_PRIV (chat);
3713
3714         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3715
3716         return priv->remote_contact;
3717 }
3718
3719 GtkWidget *
3720 empathy_chat_get_contact_menu (EmpathyChat *chat)
3721 {
3722         EmpathyChatPriv *priv = GET_PRIV (chat);
3723         GtkWidget       *menu = NULL;
3724
3725         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3726
3727         if (priv->remote_contact) {
3728                 menu = empathy_contact_menu_new (priv->remote_contact,
3729                                                  EMPATHY_CONTACT_FEATURE_CALL |
3730                                                  EMPATHY_CONTACT_FEATURE_LOG |
3731                                                  EMPATHY_CONTACT_FEATURE_INFO |
3732                                                  EMPATHY_CONTACT_FEATURE_BLOCK);
3733         }
3734
3735         return menu;
3736 }
3737
3738 void
3739 empathy_chat_clear (EmpathyChat *chat)
3740 {
3741         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3742
3743         empathy_chat_view_clear (chat->view);
3744 }
3745
3746 void
3747 empathy_chat_scroll_down (EmpathyChat *chat)
3748 {
3749         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3750
3751         empathy_chat_view_scroll_down (chat->view);
3752 }
3753
3754 void
3755 empathy_chat_cut (EmpathyChat *chat)
3756 {
3757         GtkTextBuffer *buffer;
3758
3759         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3760
3761         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3762         if (gtk_text_buffer_get_has_selection (buffer)) {
3763                 GtkClipboard *clipboard;
3764
3765                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3766
3767                 gtk_text_buffer_cut_clipboard (buffer, clipboard, TRUE);
3768         }
3769 }
3770
3771 void
3772 empathy_chat_copy (EmpathyChat *chat)
3773 {
3774         GtkTextBuffer *buffer;
3775
3776         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3777
3778         if (empathy_chat_view_get_has_selection (chat->view)) {
3779                 empathy_chat_view_copy_clipboard (chat->view);
3780                 return;
3781         }
3782
3783         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3784         if (gtk_text_buffer_get_has_selection (buffer)) {
3785                 GtkClipboard *clipboard;
3786
3787                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3788
3789                 gtk_text_buffer_copy_clipboard (buffer, clipboard);
3790         }
3791         else {
3792                 gint start_offset;
3793                 gint end_offset;
3794                 EmpathyChatPriv *priv = GET_PRIV (chat);
3795
3796                 if (gtk_label_get_selection_bounds (GTK_LABEL (priv->label_topic),
3797                                                                &start_offset,
3798                                                                &end_offset)) {
3799                         gchar *start;
3800                         gchar *end;
3801                         gchar *selection;
3802                         const gchar *topic;
3803                         GtkClipboard *clipboard;
3804
3805                         topic = gtk_label_get_text (GTK_LABEL (priv->label_topic));
3806                         start = g_utf8_offset_to_pointer (topic, start_offset);
3807                         end = g_utf8_offset_to_pointer (topic, end_offset);
3808                         selection = g_strndup (start, end - start);
3809
3810                         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3811                         gtk_clipboard_set_text (clipboard, selection, -1);
3812
3813                         g_free (selection);
3814                 }
3815         }
3816 }
3817
3818 void
3819 empathy_chat_paste (EmpathyChat *chat)
3820 {
3821         GtkTextBuffer *buffer;
3822         GtkClipboard  *clipboard;
3823         EmpathyChatPriv *priv;
3824
3825         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3826
3827         priv = GET_PRIV (chat);
3828
3829         if (gtk_widget_get_visible (priv->search_bar)) {
3830                 empathy_search_bar_paste_clipboard (EMPATHY_SEARCH_BAR (priv->search_bar));
3831                 return;
3832         }
3833
3834         if (priv->tp_chat == NULL ||
3835             !gtk_widget_is_sensitive (chat->input_text_view))
3836                 return;
3837
3838         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3839         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3840
3841         gtk_text_buffer_paste_clipboard (buffer, clipboard, NULL, TRUE);
3842 }
3843
3844 void
3845 empathy_chat_find (EmpathyChat *chat)
3846 {
3847         EmpathyChatPriv *priv;
3848
3849         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3850
3851         priv = GET_PRIV (chat);
3852
3853         empathy_search_bar_show (EMPATHY_SEARCH_BAR (priv->search_bar));
3854 }
3855
3856 void
3857 empathy_chat_correct_word (EmpathyChat  *chat,
3858                           GtkTextIter *start,
3859                           GtkTextIter *end,
3860                           const gchar *new_word)
3861 {
3862         GtkTextBuffer *buffer;
3863
3864         g_return_if_fail (chat != NULL);
3865         g_return_if_fail (new_word != NULL);
3866
3867         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3868
3869         gtk_text_buffer_delete (buffer, start, end);
3870         gtk_text_buffer_insert (buffer, start,
3871                                 new_word,
3872                                 -1);
3873 }
3874
3875 gboolean
3876 empathy_chat_is_room (EmpathyChat *chat)
3877 {
3878         EmpathyChatPriv *priv = GET_PRIV (chat);
3879
3880         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
3881
3882         return (priv->handle_type == TP_HANDLE_TYPE_ROOM);
3883 }
3884
3885 guint
3886 empathy_chat_get_nb_unread_messages (EmpathyChat *self)
3887 {
3888         EmpathyChatPriv *priv = GET_PRIV (self);
3889
3890         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
3891
3892         return priv->unread_messages;
3893 }
3894
3895 /* called when the messages have been read by user */
3896 void
3897 empathy_chat_messages_read (EmpathyChat *self)
3898 {
3899         EmpathyChatPriv *priv = GET_PRIV (self);
3900
3901         g_return_if_fail (EMPATHY_IS_CHAT (self));
3902
3903         /* FIXME: See Bug#610994, See comments about it in EmpathyChatPriv
3904          * definition. If we are still retrieving the backlogs, do not ACK */
3905         if (priv->retrieving_backlogs)
3906                 return;
3907
3908         if (priv->tp_chat != NULL ) {
3909                 empathy_tp_chat_acknowledge_all_messages (priv->tp_chat);
3910         }
3911
3912         empathy_chat_view_focus_toggled (self->view, TRUE);
3913 }
3914
3915 /* Return TRUE if on of the contacts in this chat is composing */
3916 gboolean
3917 empathy_chat_is_composing (EmpathyChat *chat)
3918 {
3919   return chat->priv->compositors != NULL;
3920 }
3921
3922 gboolean
3923 empathy_chat_is_sms_channel (EmpathyChat *self)
3924 {
3925         EmpathyChatPriv *priv = GET_PRIV (self);
3926
3927         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
3928
3929         return priv->sms_channel;
3930 }
3931
3932 guint
3933 empathy_chat_get_n_messages_sending (EmpathyChat *self)
3934 {
3935         EmpathyChatPriv *priv;
3936
3937         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
3938
3939         priv = GET_PRIV (self);
3940
3941         if (priv->tp_chat == NULL) {
3942                 return 0;
3943         } else {
3944                 guint n_messages;
3945
3946                 g_object_get (priv->tp_chat,
3947                         "n-messages-sending", &n_messages,
3948                         NULL);
3949
3950                 return n_messages;
3951         }
3952 }