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