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