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