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