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