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