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