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