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