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