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