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