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