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