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