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