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