]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-chat.c
coding style fix
[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         /* Source func ID for chat_contacts_visible_timeout_cb () */
110         guint              contacts_visible_id;
111
112         GtkWidget         *widget;
113         GtkWidget         *hpaned;
114         GtkWidget         *vbox_left;
115         GtkWidget         *scrolled_window_chat;
116         GtkWidget         *scrolled_window_input;
117         GtkWidget         *scrolled_window_contacts;
118         GtkWidget         *hbox_topic;
119         GtkWidget         *expander_topic;
120         GtkWidget         *label_topic;
121         GtkWidget         *contact_list_view;
122         GtkWidget         *info_bar_vbox;
123         GtkWidget         *search_bar;
124
125         guint              unread_messages;
126         guint              unread_messages_when_offline;
127         /* TRUE if the pending messages can be displayed. This is to avoid to show
128          * pending messages *before* messages from logs. (#603980) */
129         gboolean           can_show_pending;
130
131         /* FIXME: retrieving_backlogs flag is a workaround for Bug#610994 and should
132          * be differently handled since it introduces another race condition, which
133          * is really hard to occur, but still possible.
134          *
135          * With the current workaround (which has the race above), we need to be
136          * sure to ACK any pending messages only when the retrieval of backlogs is
137          * finished, that's why using retrieving_backlogs flag.
138          * empathy_chat_messages_read () will check this variable and not ACK
139          * anything when TRUE. It will be set TRUE at chat_constructed () and set
140          * back to FALSE when the backlog has been retrieved and the pending
141          * messages actually showed to the user.
142          *
143          * Race condition introduced with this workaround:
144          * Scenario: a message is pending, the user is notified and selects the tab.
145          * the tab with a pending message is focused before the messages are properly
146          * shown (since the preparation of the window is slower AND async WRT the
147          * tab showing), which means the user won't see any new messages (rare but
148          * possible), if he/she will change tab focus before the messages are
149          * properly shown, the tab will be set as 'seen' and the user won't be
150          * notified again about the already notified pending messages when the
151          * messages in tab will be properly shown */
152         gboolean           retrieving_backlogs;
153         gboolean           sms_channel;
154
155         /* we need to know whether populate-popup happened in response to
156          * the keyboard or the mouse. We can't ask GTK for the most recent
157          * event, because it will be a notify event. Instead we track it here */
158         GdkEventType       most_recent_event_type;
159 };
160
161 typedef struct {
162         gchar *text; /* Original message that was specified
163                       * upon entry creation. */
164         gchar *modified_text; /* Message that was modified by user.
165                                * When no modifications were made, it is NULL */
166 } InputHistoryEntry;
167
168 enum {
169         COMPOSING,
170         NEW_MESSAGE,
171         PART_COMMAND_ENTERED,
172         LAST_SIGNAL
173 };
174
175 enum {
176         PROP_0,
177         PROP_TP_CHAT,
178         PROP_ACCOUNT,
179         PROP_ID,
180         PROP_NAME,
181         PROP_SUBJECT,
182         PROP_REMOTE_CONTACT,
183         PROP_SHOW_CONTACTS,
184         PROP_SMS_CHANNEL,
185         PROP_N_MESSAGES_SENDING,
186         PROP_NB_UNREAD_MESSAGES,
187 };
188
189 static guint signals[LAST_SIGNAL] = { 0 };
190
191 G_DEFINE_TYPE (EmpathyChat, empathy_chat, GTK_TYPE_BOX);
192
193 static gboolean update_misspelled_words (gpointer data);
194
195 static void
196 chat_get_property (GObject    *object,
197                    guint       param_id,
198                    GValue     *value,
199                    GParamSpec *pspec)
200 {
201         EmpathyChat *chat = EMPATHY_CHAT (object);
202         EmpathyChatPriv *priv = GET_PRIV (object);
203
204         switch (param_id) {
205         case PROP_TP_CHAT:
206                 g_value_set_object (value, priv->tp_chat);
207                 break;
208         case PROP_ACCOUNT:
209                 g_value_set_object (value, priv->account);
210                 break;
211         case PROP_NAME:
212                 g_value_take_string (value, empathy_chat_dup_name (chat));
213                 break;
214         case PROP_ID:
215                 g_value_set_string (value, priv->id);
216                 break;
217         case PROP_SUBJECT:
218                 g_value_set_string (value, priv->subject);
219                 break;
220         case PROP_REMOTE_CONTACT:
221                 g_value_set_object (value, priv->remote_contact);
222                 break;
223         case PROP_SHOW_CONTACTS:
224                 g_value_set_boolean (value, priv->show_contacts);
225                 break;
226         case PROP_SMS_CHANNEL:
227                 g_value_set_boolean (value, priv->sms_channel);
228                 break;
229         case PROP_N_MESSAGES_SENDING:
230                 g_value_set_uint (value,
231                         empathy_chat_get_n_messages_sending (chat));
232                 break;
233         case PROP_NB_UNREAD_MESSAGES:
234                 g_value_set_uint (value,
235                         empathy_chat_get_nb_unread_messages (chat));
236                 break;
237         default:
238                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
239                 break;
240         };
241 }
242
243 static void
244 chat_set_property (GObject      *object,
245                    guint         param_id,
246                    const GValue *value,
247                    GParamSpec   *pspec)
248 {
249         EmpathyChat *chat = EMPATHY_CHAT (object);
250
251         switch (param_id) {
252         case PROP_TP_CHAT:
253                 empathy_chat_set_tp_chat (chat, EMPATHY_TP_CHAT (g_value_get_object (value)));
254                 break;
255         case PROP_SHOW_CONTACTS:
256                 empathy_chat_set_show_contacts (chat, g_value_get_boolean (value));
257                 break;
258         default:
259                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
260                 break;
261         };
262 }
263
264 static void
265 account_reconnected (EmpathyChat *chat,
266                         TpAccount *account)
267 {
268         EmpathyChatPriv *priv = GET_PRIV (chat);
269
270         DEBUG ("Account reconnected, request a new Text channel");
271
272         /* FIXME: Ideally we should ask to handle ourself the channel so we can
273         * report the error if any but this is blocked by
274         * https://bugs.freedesktop.org/show_bug.cgi?id=13422 */
275         switch (priv->handle_type) {
276                 case TP_HANDLE_TYPE_CONTACT:
277                         if (priv->sms_channel)
278                                 empathy_sms_contact_id (
279                                         account, priv->id,
280                                         TP_USER_ACTION_TIME_NOT_USER_ACTION);
281                         else
282                                 empathy_chat_with_contact_id (
283                                         account, priv->id,
284                                         TP_USER_ACTION_TIME_NOT_USER_ACTION);
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
1018 chat_command_whale (EmpathyChat *chat,
1019                     GStrv        strv)
1020 {
1021         EmpathyChatPriv *priv = GET_PRIV (chat);
1022         TpMessage *message;
1023
1024         message = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,
1025                 "\n\n\n"
1026                 "•_______________•");
1027         empathy_tp_chat_send (priv->tp_chat, message);
1028         g_object_unref (message);
1029 }
1030
1031 static void
1032 chat_command_babywhale (EmpathyChat *chat,
1033                         GStrv        strv)
1034 {
1035         EmpathyChatPriv *priv = GET_PRIV (chat);
1036         TpMessage *message;
1037
1038         message = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,
1039                 "\n"
1040                 "•_____•");
1041         empathy_tp_chat_send (priv->tp_chat, message);
1042         g_object_unref (message);
1043 }
1044
1045 static void chat_command_help (EmpathyChat *chat, GStrv strv);
1046
1047 typedef void (*ChatCommandFunc) (EmpathyChat *chat, GStrv strv);
1048
1049 typedef struct {
1050         const gchar *prefix;
1051         guint min_parts;
1052         guint max_parts;
1053         ChatCommandFunc func;
1054         gboolean (*is_supported)(EmpathyChat *chat);
1055         const gchar *help;
1056 } ChatCommandItem;
1057
1058 static ChatCommandItem commands[] = {
1059         {"clear", 1, 1, chat_command_clear, NULL,
1060          N_("/clear: clear all messages from the current conversation")},
1061
1062         {"topic", 2, 2, chat_command_topic, NULL,
1063          N_("/topic <topic>: set the topic of the current conversation")},
1064
1065         {"join", 2, 2, chat_command_join, NULL,
1066          N_("/join <chat room ID>: join a new chat room")},
1067
1068         {"j", 2, 2, chat_command_join, NULL,
1069          N_("/j <chat room ID>: join a new chat room")},
1070
1071         /* FIXME: https://bugzilla.gnome.org/show_bug.cgi?id=643295 */
1072         {"part", 1, 3, chat_command_part, part_command_supported,
1073          N_("/part [<chat room ID>] [<reason>]: leave the chat room, "
1074             "by default the current one")},
1075
1076         {"query", 2, 3, chat_command_query, NULL,
1077          N_("/query <contact ID> [<message>]: open a private chat")},
1078
1079         {"msg", 3, 3, chat_command_msg, NULL,
1080          N_("/msg <contact ID> <message>: open a private chat")},
1081
1082         {"nick", 2, 2, chat_command_nick, nick_command_supported,
1083          N_("/nick <nickname>: change your nickname on the current server")},
1084
1085         {"me", 2, 2, chat_command_me, NULL,
1086          N_("/me <message>: send an ACTION message to the current conversation")},
1087
1088         {"say", 2, 2, chat_command_say, NULL,
1089          N_("/say <message>: send <message> to the current conversation. "
1090             "This is used to send a message starting with a '/'. For example: "
1091             "\"/say /join is used to join a new chat room\"")},
1092
1093         {"whois", 2, 2, chat_command_whois, NULL,
1094          N_("/whois <contact ID>: display information about a contact")},
1095
1096         {"help", 1, 2, chat_command_help, NULL,
1097          N_("/help [<command>]: show all supported commands. "
1098             "If <command> is defined, show its usage.")},
1099
1100         {"whale", 1, 1, chat_command_whale, NULL, NULL},
1101         {"babywhale", 1, 1, chat_command_babywhale, NULL, NULL},
1102 };
1103
1104 static void
1105 chat_command_show_help (EmpathyChat     *chat,
1106                         ChatCommandItem *item)
1107 {
1108         gchar *str;
1109
1110         if (item->help == NULL) {
1111                 return;
1112         }
1113
1114         str = g_strdup_printf (_("Usage: %s"), _(item->help));
1115         empathy_chat_view_append_event (chat->view, str);
1116         g_free (str);
1117 }
1118
1119 static void
1120 chat_command_help (EmpathyChat *chat,
1121                    GStrv        strv)
1122 {
1123         guint i;
1124
1125         /* If <command> part is not defined,
1126          * strv[1] will be the terminal NULL */
1127         if (strv[1] == NULL) {
1128                 for (i = 0; i < G_N_ELEMENTS (commands); i++) {
1129                         if (commands[i].is_supported != NULL) {
1130                                 if (!commands[i].is_supported (chat)) {
1131                                         continue;
1132                                 }
1133                         }
1134                         if (commands[i].help == NULL) {
1135                                 continue;
1136                         }
1137                         empathy_chat_view_append_event (chat->view,
1138                                 _(commands[i].help));
1139                 }
1140                 return;
1141         }
1142
1143         for (i = 0; i < G_N_ELEMENTS (commands); i++) {
1144                 if (g_ascii_strcasecmp (strv[1], commands[i].prefix) == 0) {
1145                         if (commands[i].is_supported != NULL) {
1146                                 if (!commands[i].is_supported (chat)) {
1147                                         break;
1148                                 }
1149                         }
1150                         if (commands[i].help == NULL) {
1151                                 break;
1152                         }
1153                         chat_command_show_help (chat, &commands[i]);
1154                         return;
1155                 }
1156         }
1157
1158         empathy_chat_view_append_event (chat->view,
1159                 _("Unknown command"));
1160 }
1161
1162 static GStrv
1163 chat_command_parse (const gchar *text, guint max_parts)
1164 {
1165         GPtrArray *array;
1166         gchar *item;
1167
1168         DEBUG ("Parse command, parts=%d text=\"%s\":", max_parts, text);
1169
1170         array = g_ptr_array_sized_new (max_parts + 1);
1171         while (max_parts > 1) {
1172                 const gchar *end;
1173
1174                 /* Skip white spaces */
1175                 while (g_ascii_isspace (*text)) {
1176                         text++;
1177                 }
1178
1179                 /* Search the end of this part, until first space. */
1180                 for (end = text; *end != '\0' && !g_ascii_isspace (*end); end++)
1181                         /* Do nothing */;
1182                 if (*end == '\0') {
1183                         break;
1184                 }
1185
1186                 item = g_strndup (text, end - text);
1187                 g_ptr_array_add (array, item);
1188                 DEBUG ("\tITEM: \"%s\"", item);
1189
1190                 text = end;
1191                 max_parts--;
1192         }
1193
1194         /* Append last part if not empty */
1195         item = g_strstrip (g_strdup (text));
1196         if (!EMP_STR_EMPTY (item)) {
1197                 g_ptr_array_add (array, item);
1198                 DEBUG ("\tITEM: \"%s\"", item);
1199         } else {
1200                 g_free (item);
1201         }
1202
1203         /* Make the array NULL-terminated */
1204         g_ptr_array_add (array, NULL);
1205
1206         return (GStrv) g_ptr_array_free (array, FALSE);
1207 }
1208
1209 static gboolean
1210 has_prefix_case (const gchar *s,
1211                   const gchar *prefix)
1212 {
1213         return g_ascii_strncasecmp (s, prefix, strlen (prefix)) == 0;
1214 }
1215
1216 static void
1217 chat_send (EmpathyChat  *chat,
1218            const gchar *msg)
1219 {
1220         EmpathyChatPriv *priv;
1221         TpMessage  *message;
1222         guint            i;
1223
1224         if (EMP_STR_EMPTY (msg)) {
1225                 return;
1226         }
1227
1228         priv = GET_PRIV (chat);
1229
1230         chat_input_history_add (chat, msg, FALSE);
1231
1232         if (msg[0] == '/') {
1233                 gboolean second_slash = FALSE;
1234                 const gchar *iter = msg + 1;
1235
1236                 for (i = 0; i < G_N_ELEMENTS (commands); i++) {
1237                         GStrv strv;
1238                         guint strv_len;
1239                         gchar c;
1240
1241                         if (!has_prefix_case (msg + 1, commands[i].prefix)) {
1242                                 continue;
1243                         }
1244                         c = *(msg + 1 + strlen (commands[i].prefix));
1245                         if (c != '\0' && !g_ascii_isspace (c)) {
1246                                 continue;
1247                         }
1248                         if (commands[i].is_supported != NULL) {
1249                                 if (!commands[i].is_supported (chat)) {
1250                                         continue;
1251                                 }
1252                         }
1253
1254                         /* We can't use g_strsplit here because it does
1255                          * not deal correctly if we have more than one space
1256                          * between args */
1257                         strv = chat_command_parse (msg + 1, commands[i].max_parts);
1258
1259                         strv_len = g_strv_length (strv);
1260                         if (strv_len < commands[i].min_parts ||
1261                             strv_len > commands[i].max_parts) {
1262                                 chat_command_show_help (chat, &commands[i]);
1263                                 g_strfreev (strv);
1264                                 return;
1265                         }
1266
1267                         commands[i].func (chat, strv);
1268                         g_strfreev (strv);
1269                         return;
1270                 }
1271
1272                 /* Also allow messages with two slashes before the
1273                  * first space, so it is possible to send a /unix/path.
1274                  * This heuristic is kind of crap. */
1275                 while (*iter != '\0' && !g_ascii_isspace (*iter)) {
1276                         if (*iter == '/') {
1277                                 second_slash = TRUE;
1278                                 break;
1279                         }
1280                         iter++;
1281                 }
1282
1283                 if (!second_slash) {
1284                         empathy_chat_view_append_event (chat->view,
1285                                 _("Unknown command; see /help for the available"
1286                                   " commands"));
1287                         return;
1288                 }
1289         }
1290
1291         message = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,
1292                 msg);
1293         empathy_tp_chat_send (priv->tp_chat, message);
1294         g_object_unref (message);
1295 }
1296
1297 static void
1298 chat_input_text_view_send (EmpathyChat *chat)
1299 {
1300         GtkTextBuffer  *buffer;
1301         GtkTextIter     start, end;
1302         gchar          *msg;
1303
1304         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1305
1306         gtk_text_buffer_get_bounds (buffer, &start, &end);
1307         msg = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1308
1309         /* clear the input field */
1310         gtk_text_buffer_set_text (buffer, "", -1);
1311         /* delete input history modifications */
1312         chat_input_history_revert (chat);
1313
1314         chat_send (chat, msg);
1315         g_free (msg);
1316 }
1317
1318 static void
1319 chat_state_changed_cb (EmpathyTpChat      *tp_chat,
1320                        EmpathyContact     *contact,
1321                        TpChannelChatState  state,
1322                        EmpathyChat        *chat)
1323 {
1324         EmpathyChatPriv *priv;
1325         GList          *l;
1326         gboolean        was_composing;
1327
1328         priv = GET_PRIV (chat);
1329
1330         if (empathy_contact_is_user (contact)) {
1331                 /* We don't care about our own chat state */
1332                 return;
1333         }
1334
1335         was_composing = (priv->compositors != NULL);
1336
1337         /* Find the contact in the list. After that l is the list elem or NULL */
1338         for (l = priv->compositors; l; l = l->next) {
1339                 if (contact == l->data) {
1340                         break;
1341                 }
1342         }
1343
1344         switch (state) {
1345         case TP_CHANNEL_CHAT_STATE_GONE:
1346         case TP_CHANNEL_CHAT_STATE_INACTIVE:
1347         case TP_CHANNEL_CHAT_STATE_PAUSED:
1348         case TP_CHANNEL_CHAT_STATE_ACTIVE:
1349                 /* Contact is not composing */
1350                 if (l) {
1351                         priv->compositors = g_list_remove_link (priv->compositors, l);
1352                         g_object_unref (l->data);
1353                         g_list_free1 (l);
1354                 }
1355                 break;
1356         case TP_CHANNEL_CHAT_STATE_COMPOSING:
1357                 /* Contact is composing */
1358                 if (!l) {
1359                         priv->compositors = g_list_prepend (priv->compositors,
1360                                                             g_object_ref (contact));
1361                 }
1362                 break;
1363         default:
1364                 g_assert_not_reached ();
1365         }
1366
1367         DEBUG ("Was composing: %s now composing: %s",
1368                 was_composing ? "yes" : "no",
1369                 priv->compositors ? "yes" : "no");
1370
1371         if ((was_composing && !priv->compositors) ||
1372             (!was_composing && priv->compositors)) {
1373                 /* Composing state changed */
1374                 g_signal_emit (chat, signals[COMPOSING], 0,
1375                                priv->compositors != NULL);
1376         }
1377 }
1378
1379 static void
1380 chat_message_received (EmpathyChat *chat,
1381         EmpathyMessage *message,
1382         gboolean pending)
1383 {
1384         EmpathyChatPriv *priv = GET_PRIV (chat);
1385         EmpathyContact  *sender;
1386
1387         sender = empathy_message_get_sender (message);
1388
1389         if (empathy_message_is_edit (message)) {
1390                 DEBUG ("Editing message '%s' to '%s'",
1391                         empathy_message_get_supersedes (message),
1392                         empathy_message_get_body (message));
1393
1394                 empathy_chat_view_edit_message (chat->view, message);
1395         } else {
1396                 DEBUG ("Appending new message '%s' from %s (%d)",
1397                         empathy_message_get_token (message),
1398                         empathy_contact_get_alias (sender),
1399                         empathy_contact_get_handle (sender));
1400
1401                 empathy_chat_view_append_message (chat->view, message);
1402
1403                 if (empathy_message_is_incoming (message)) {
1404                         priv->unread_messages++;
1405                         g_object_notify (G_OBJECT (chat), "nb-unread-messages");
1406                 }
1407
1408                 g_signal_emit (chat, signals[NEW_MESSAGE], 0, message, pending);
1409         }
1410
1411         /* We received a message so the contact is no longer
1412          * composing */
1413         chat_state_changed_cb (priv->tp_chat, sender,
1414                                TP_CHANNEL_CHAT_STATE_ACTIVE,
1415                                chat);
1416 }
1417
1418 static void
1419 chat_message_received_cb (EmpathyTpChat  *tp_chat,
1420                           EmpathyMessage *message,
1421                           EmpathyChat    *chat)
1422 {
1423         chat_message_received (chat, message, FALSE);
1424 }
1425
1426 static void
1427 chat_message_acknowledged_cb (EmpathyTpChat  *tp_chat,
1428                               EmpathyMessage *message,
1429                               EmpathyChat    *chat)
1430 {
1431         EmpathyChatPriv *priv = GET_PRIV (chat);
1432
1433         empathy_chat_view_message_acknowledged (chat->view,
1434             message);
1435
1436         if (!empathy_message_is_edit (message)) {
1437                 priv->unread_messages--;
1438                 g_object_notify (G_OBJECT (chat), "nb-unread-messages");
1439         }
1440 }
1441
1442 static void
1443 chat_send_error_cb (EmpathyTpChat          *tp_chat,
1444                     const gchar            *message_body,
1445                     TpChannelTextSendError  error_code,
1446                     const gchar            *dbus_error,
1447                     EmpathyChat            *chat)
1448 {
1449         const gchar *error = NULL;
1450         gchar       *str;
1451
1452         if (!tp_strdiff (dbus_error, TP_ERROR_STR_INSUFFICIENT_BALANCE)) {
1453                 /* translators: error used when user doesn't have enough credit on his
1454                  * account to send the message. */
1455                 error = _("insufficient balance to send message");
1456         } else if (!tp_strdiff (dbus_error, TP_ERROR_STR_NOT_CAPABLE)) {
1457                 error = _("not capable");
1458         }
1459
1460         if (error == NULL) {
1461                 /* if we didn't find a dbus-error, try the old error */
1462                 switch (error_code) {
1463                 case TP_CHANNEL_TEXT_SEND_ERROR_OFFLINE:
1464                         error = _("offline");
1465                         break;
1466                 case TP_CHANNEL_TEXT_SEND_ERROR_INVALID_CONTACT:
1467                         error = _("invalid contact");
1468                         break;
1469                 case TP_CHANNEL_TEXT_SEND_ERROR_PERMISSION_DENIED:
1470                         error = _("permission denied");
1471                         break;
1472                 case TP_CHANNEL_TEXT_SEND_ERROR_TOO_LONG:
1473                         error = _("too long message");
1474                         break;
1475                 case TP_CHANNEL_TEXT_SEND_ERROR_NOT_IMPLEMENTED:
1476                         error = _("not implemented");
1477                         break;
1478                 case TP_CHANNEL_TEXT_SEND_ERROR_UNKNOWN:
1479                 default:
1480                         error = _("unknown");
1481                         break;
1482                 }
1483         }
1484
1485         if (message_body != NULL) {
1486                         str = g_strdup_printf (_("Error sending message '%s': %s"),
1487                                 message_body, error);
1488         }
1489         else {
1490                         str = g_strdup_printf (_("Error sending message: %s"), error);
1491         }
1492
1493         empathy_chat_view_append_event (chat->view, str);
1494         g_free (str);
1495 }
1496
1497 static void
1498 chat_topic_label_size_allocate_cb (GtkLabel *label,
1499                                    GtkAllocation *allocation,
1500                                    EmpathyChat *chat)
1501 {
1502         EmpathyChatPriv *priv = GET_PRIV (chat);
1503
1504         if (!gtk_label_get_line_wrap (label)) {
1505                 if (pango_layout_is_ellipsized (gtk_label_get_layout (label)))
1506                         gtk_widget_show (priv->expander_topic);
1507                 else
1508                         gtk_widget_hide (priv->expander_topic);
1509
1510                 return;
1511         }
1512 }
1513
1514 static void
1515 chat_topic_expander_activate_cb (GtkExpander *expander,
1516                                  GParamSpec *param_spec,
1517                                  EmpathyChat *chat)
1518 {
1519         EmpathyChatPriv *priv = GET_PRIV (chat);
1520
1521         if (gtk_expander_get_expanded (expander)) {
1522                 gtk_label_set_ellipsize (GTK_LABEL (priv->label_topic), PANGO_ELLIPSIZE_NONE);
1523                 gtk_label_set_line_wrap (GTK_LABEL (priv->label_topic), TRUE);
1524         } else {
1525                 gtk_label_set_ellipsize (GTK_LABEL (priv->label_topic), PANGO_ELLIPSIZE_END);
1526                 gtk_label_set_line_wrap (GTK_LABEL (priv->label_topic), FALSE);
1527         }
1528 }
1529
1530 static void
1531 chat_property_changed_cb (EmpathyTpChat *tp_chat,
1532                           const gchar   *name,
1533                           GValue        *value,
1534                           EmpathyChat   *chat)
1535 {
1536         EmpathyChatPriv *priv = GET_PRIV (chat);
1537
1538         if (!tp_strdiff (name, "subject")) {
1539                 g_free (priv->subject);
1540                 priv->subject = g_value_dup_string (value);
1541                 g_object_notify (G_OBJECT (chat), "subject");
1542
1543                 if (EMP_STR_EMPTY (priv->subject)) {
1544                         gtk_widget_hide (priv->hbox_topic);
1545                 } else {
1546                         gchar *markup_topic;
1547                         gchar *markup_text;
1548
1549                         markup_topic = empathy_add_link_markup (priv->subject);
1550                         markup_text = g_strdup_printf ("<span weight=\"bold\">%s</span> %s",
1551                                 _("Topic:"), markup_topic);
1552
1553                         gtk_label_set_markup (GTK_LABEL (priv->label_topic), markup_text);
1554                         g_free (markup_text);
1555                         g_free (markup_topic);
1556
1557                         gtk_widget_show (priv->hbox_topic);
1558                 }
1559                 if (priv->block_events_timeout_id == 0) {
1560                         gchar *str;
1561
1562                         if (!EMP_STR_EMPTY (priv->subject)) {
1563                                 str = g_strdup_printf (_("Topic set to: %s"), priv->subject);
1564                         } else {
1565                                 str = g_strdup (_("No topic defined"));
1566                         }
1567                         empathy_chat_view_append_event (EMPATHY_CHAT (chat)->view, str);
1568                         g_free (str);
1569                 }
1570         }
1571         else if (!tp_strdiff (name, "name")) {
1572                 g_free (priv->name);
1573                 priv->name = g_value_dup_string (value);
1574                 g_object_notify (G_OBJECT (chat), "name");
1575         }
1576 }
1577
1578 static gboolean
1579 chat_input_text_get_word_from_iter (GtkTextIter   *iter,
1580                                     GtkTextIter   *start,
1581                                     GtkTextIter   *end)
1582 {
1583         GtkTextIter word_start = *iter;
1584         GtkTextIter word_end = *iter;
1585         GtkTextIter tmp;
1586
1587         if (gtk_text_iter_inside_word (&word_end) &&
1588                         !gtk_text_iter_ends_word (&word_end)) {
1589                 gtk_text_iter_forward_word_end (&word_end);
1590         }
1591
1592         tmp = word_end;
1593
1594         if (gtk_text_iter_get_char (&tmp) == '\'') {
1595                 gtk_text_iter_forward_char (&tmp);
1596
1597                 if (g_unichar_isalpha (gtk_text_iter_get_char (&tmp))) {
1598                         gtk_text_iter_forward_word_end (&word_end);
1599                 }
1600         }
1601
1602
1603         if (gtk_text_iter_inside_word (&word_start) ||
1604                         gtk_text_iter_ends_word (&word_start)) {
1605                 if (!gtk_text_iter_starts_word (&word_start) ||
1606                                 gtk_text_iter_equal (&word_start, &word_end)) {
1607                         gtk_text_iter_backward_word_start (&word_start);
1608                 }
1609
1610                 tmp = word_start;
1611                 gtk_text_iter_backward_char (&tmp);
1612
1613                 if (gtk_text_iter_get_char (&tmp) == '\'') {
1614                         gtk_text_iter_backward_char (&tmp);
1615
1616                         if (g_unichar_isalpha (gtk_text_iter_get_char (&tmp))) {
1617                                 gtk_text_iter_backward_word_start (&word_start);
1618                         }
1619                 }
1620         }
1621
1622         *start = word_start;
1623         *end = word_end;
1624         return TRUE;
1625 }
1626
1627 static void
1628 chat_input_text_buffer_insert_text_cb (GtkTextBuffer *buffer,
1629                                        GtkTextIter   *location,
1630                                        gchar         *text,
1631                                        gint           len,
1632                                        EmpathyChat   *chat)
1633 {
1634         GtkTextIter iter, pos;
1635
1636         /* Remove all misspelled tags in the inserted text.
1637          * This happens when text is inserted within a misspelled word. */
1638         gtk_text_buffer_get_iter_at_offset (buffer, &iter,
1639                                             gtk_text_iter_get_offset (location) - len);
1640         gtk_text_buffer_remove_tag_by_name (buffer, "misspelled",
1641                                             &iter, location);
1642
1643         gtk_text_buffer_get_iter_at_mark (buffer, &pos, gtk_text_buffer_get_insert (buffer));
1644
1645         do {
1646                 GtkTextIter start, end;
1647                 gchar *str;
1648
1649                 if (!chat_input_text_get_word_from_iter (&iter, &start, &end))
1650                         continue;
1651
1652                 str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1653
1654                 if (gtk_text_iter_in_range (&pos, &start, &end) ||
1655                                 gtk_text_iter_equal (&pos, &end) ||
1656                                 empathy_spell_check (str)) {
1657                         gtk_text_buffer_remove_tag_by_name (buffer, "misspelled", &start, &end);
1658                 } else {
1659                         gtk_text_buffer_apply_tag_by_name (buffer, "misspelled", &start, &end);
1660                 }
1661
1662                 g_free (str);
1663
1664         } while (gtk_text_iter_forward_word_end (&iter) &&
1665                  gtk_text_iter_compare (&iter, location) <= 0);
1666 }
1667
1668 static void
1669 chat_input_text_buffer_delete_range_cb (GtkTextBuffer *buffer,
1670                                         GtkTextIter   *start,
1671                                         GtkTextIter   *end,
1672                                         EmpathyChat   *chat)
1673 {
1674         GtkTextIter word_start, word_end;
1675
1676         if (chat_input_text_get_word_from_iter (start, &word_start, &word_end)) {
1677                 gtk_text_buffer_remove_tag_by_name (buffer, "misspelled",
1678                                                     &word_start, &word_end);
1679         }
1680 }
1681
1682 static void
1683 chat_input_text_buffer_changed_cb (GtkTextBuffer *buffer,
1684                                    EmpathyChat    *chat)
1685 {
1686         if (gtk_text_buffer_get_char_count (buffer) == 0) {
1687                 chat_composing_stop (chat);
1688         } else {
1689                 chat_composing_start (chat);
1690         }
1691 }
1692
1693 static void
1694 chat_input_text_buffer_notify_cursor_position_cb (GtkTextBuffer *buffer,
1695                                                   GParamSpec    *pspec,
1696                                                   EmpathyChat    *chat)
1697 {
1698         GtkTextIter pos;
1699         GtkTextIter prev_pos;
1700         GtkTextIter word_start;
1701         GtkTextIter word_end;
1702         GtkTextMark *mark;
1703         gchar *str;
1704
1705         mark = gtk_text_buffer_get_mark (buffer, "previous-cursor-position");
1706
1707         gtk_text_buffer_get_iter_at_mark (buffer, &pos,
1708                                           gtk_text_buffer_get_insert (buffer));
1709         gtk_text_buffer_get_iter_at_mark (buffer, &prev_pos, mark);
1710
1711         if (!chat_input_text_get_word_from_iter (&prev_pos, &word_start, &word_end))
1712                 goto out;
1713
1714         if (!gtk_text_iter_in_range (&pos, &word_start, &word_end) &&
1715                         !gtk_text_iter_equal (&pos, &word_end)) {
1716                 str = gtk_text_buffer_get_text (buffer,
1717                                         &word_start, &word_end, FALSE);
1718
1719                 if (!empathy_spell_check (str)) {
1720                         gtk_text_buffer_apply_tag_by_name (buffer,
1721                                         "misspelled", &word_start, &word_end);
1722                 } else {
1723                         gtk_text_buffer_remove_tag_by_name (buffer,
1724                                         "misspelled", &word_start, &word_end);
1725                 }
1726
1727                 g_free (str);
1728         }
1729
1730 out:
1731         gtk_text_buffer_move_mark (buffer, mark, &pos);
1732 }
1733
1734 static gboolean
1735 empathy_isspace_cb (gunichar c,
1736                  gpointer data)
1737 {
1738         return g_unichar_isspace (c);
1739 }
1740
1741 static gboolean
1742 chat_input_key_press_event_cb (GtkWidget   *widget,
1743                                GdkEventKey *event,
1744                                EmpathyChat *chat)
1745 {
1746         EmpathyChatPriv *priv;
1747         GtkAdjustment  *adj;
1748         gdouble         val;
1749         GtkWidget      *text_view_sw;
1750
1751         priv = GET_PRIV (chat);
1752
1753         priv->most_recent_event_type = event->type;
1754
1755         /* Catch ctrl+up/down so we can traverse messages we sent */
1756         if ((event->state & GDK_CONTROL_MASK) &&
1757             (event->keyval == GDK_KEY_Up ||
1758              event->keyval == GDK_KEY_Down)) {
1759                 GtkTextBuffer *buffer;
1760                 const gchar   *str;
1761
1762                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1763                 chat_input_history_update (chat, buffer);
1764
1765                 if (event->keyval == GDK_KEY_Up) {
1766                         str = chat_input_history_get_next (chat);
1767                 } else {
1768                         str = chat_input_history_get_prev (chat);
1769                 }
1770
1771                 g_signal_handlers_block_by_func (buffer,
1772                                                  chat_input_text_buffer_changed_cb,
1773                                                  chat);
1774                 gtk_text_buffer_set_text (buffer, str ? str : "", -1);
1775                 g_signal_handlers_unblock_by_func (buffer,
1776                                                    chat_input_text_buffer_changed_cb,
1777                                                    chat);
1778
1779                 return TRUE;
1780         }
1781
1782         /* Catch enter but not ctrl/shift-enter */
1783         if (IS_ENTER (event->keyval) &&
1784             !(event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
1785                 GtkTextView *view;
1786
1787                 /* This is to make sure that kinput2 gets the enter. And if
1788                  * it's handled there we shouldn't send on it. This is because
1789                  * kinput2 uses Enter to commit letters. See:
1790                  * http://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=104299
1791                  */
1792
1793                 view = GTK_TEXT_VIEW (chat->input_text_view);
1794                 if (gtk_text_view_im_context_filter_keypress (view, event)) {
1795                         gtk_text_view_reset_im_context (view);
1796                         return TRUE;
1797                 }
1798
1799                 chat_input_text_view_send (chat);
1800                 return TRUE;
1801         }
1802
1803         text_view_sw = gtk_widget_get_parent (GTK_WIDGET (chat->view));
1804
1805         if (IS_ENTER (event->keyval) &&
1806             (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
1807                 /* Newline for shift/control-enter. */
1808                 return FALSE;
1809         }
1810         if (!(event->state & GDK_CONTROL_MASK) &&
1811             event->keyval == GDK_KEY_Page_Up) {
1812                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
1813                 gtk_adjustment_set_value (adj, gtk_adjustment_get_value (adj) - gtk_adjustment_get_page_size (adj));
1814                 return TRUE;
1815         }
1816         if ((event->state & GDK_CONTROL_MASK) != GDK_CONTROL_MASK &&
1817             event->keyval == GDK_KEY_Page_Down) {
1818                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
1819                 val = MIN (gtk_adjustment_get_value (adj) + gtk_adjustment_get_page_size (adj),
1820                            gtk_adjustment_get_upper (adj) - gtk_adjustment_get_page_size (adj));
1821                 gtk_adjustment_set_value (adj, val);
1822                 return TRUE;
1823         }
1824         if (event->keyval == GDK_KEY_Escape) {
1825                 empathy_search_bar_hide (EMPATHY_SEARCH_BAR (priv->search_bar));
1826         }
1827         if (!(event->state & (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) &&
1828             event->keyval == GDK_KEY_Tab) {
1829                 GtkTextBuffer *buffer;
1830                 GtkTextIter    start, current;
1831                 gchar         *nick, *completed;
1832                 GList         *list, *completed_list;
1833                 gboolean       is_start_of_buffer;
1834
1835                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (EMPATHY_CHAT (chat)->input_text_view));
1836                 gtk_text_buffer_get_iter_at_mark (buffer, &current, gtk_text_buffer_get_insert (buffer));
1837
1838                 /* Get the start of the nick to complete. */
1839                 gtk_text_buffer_get_iter_at_mark (buffer, &start, gtk_text_buffer_get_insert (buffer));
1840                 if (gtk_text_iter_backward_find_char (&start, &empathy_isspace_cb, NULL, NULL)) {
1841                         gtk_text_iter_set_offset (&start, gtk_text_iter_get_offset (&start) + 1);
1842                 }
1843                 is_start_of_buffer = gtk_text_iter_is_start (&start);
1844
1845                 list = empathy_contact_list_get_members (EMPATHY_CONTACT_LIST (priv->tp_chat));
1846                 g_completion_add_items (priv->completion, list);
1847
1848                 nick = gtk_text_buffer_get_text (buffer, &start, &current, FALSE);
1849                 completed_list = g_completion_complete (priv->completion,
1850                                                         nick,
1851                                                         &completed);
1852
1853                 g_free (nick);
1854
1855                 if (completed) {
1856                         guint        len;
1857                         const gchar *text;
1858                         GString     *message = NULL;
1859                         GList       *l;
1860
1861                         gtk_text_buffer_delete (buffer, &start, &current);
1862
1863                         len = g_list_length (completed_list);
1864
1865                         if (len == 1) {
1866                                 /* If we only have one hit, use that text
1867                                  * instead of the text in completed since the
1868                                  * completed text will use the typed string
1869                                  * which might be cased all wrong.
1870                                  * Fixes #120876
1871                                  * */
1872                                 text = empathy_contact_get_alias (completed_list->data);
1873                         } else {
1874                                 text = completed;
1875
1876                                 /* Print all hits to the scrollback view, so the
1877                                  * user knows what possibilities he has.
1878                                  * Fixes #599779
1879                                  * */
1880                                  message = g_string_new ("");
1881                                  for (l = completed_list; l != NULL; l = l->next) {
1882                                         g_string_append (message, empathy_contact_get_alias (l->data));
1883                                         g_string_append (message, " - ");
1884                                  }
1885                                  empathy_chat_view_append_event (chat->view, message->str);
1886                                  g_string_free (message, TRUE);
1887                         }
1888
1889                         gtk_text_buffer_insert_at_cursor (buffer, text, strlen (text));
1890
1891                         if (len == 1 && is_start_of_buffer) {
1892                             gchar *complete_char;
1893
1894                             complete_char = g_settings_get_string (
1895                                     priv->gsettings_chat,
1896                                     EMPATHY_PREFS_CHAT_NICK_COMPLETION_CHAR);
1897
1898                             if (complete_char != NULL) {
1899                                 gtk_text_buffer_insert_at_cursor (buffer,
1900                                                                   complete_char,
1901                                                                   strlen (complete_char));
1902                                 gtk_text_buffer_insert_at_cursor (buffer, " ", 1);
1903                                 g_free (complete_char);
1904                             }
1905                         }
1906
1907                         g_free (completed);
1908                 }
1909
1910                 g_completion_clear_items (priv->completion);
1911
1912                 g_list_foreach (list, (GFunc) g_object_unref, NULL);
1913                 g_list_free (list);
1914
1915                 return TRUE;
1916         }
1917
1918         return FALSE;
1919 }
1920
1921 static gboolean
1922 chat_text_view_focus_in_event_cb (GtkWidget  *widget,
1923                                   GdkEvent   *event,
1924                                   EmpathyChat *chat)
1925 {
1926         gtk_widget_grab_focus (chat->input_text_view);
1927
1928         return TRUE;
1929 }
1930
1931 static void
1932 chat_input_realize_cb (GtkWidget   *widget,
1933                        EmpathyChat *chat)
1934 {
1935         DEBUG ("Setting focus to the input text view");
1936         if (gtk_widget_is_sensitive (widget)) {
1937                 gtk_widget_grab_focus (widget);
1938         }
1939 }
1940
1941 static void
1942 chat_input_has_focus_notify_cb (GtkWidget   *widget,
1943                                 GParamSpec  *pspec,
1944                                 EmpathyChat *chat)
1945 {
1946         empathy_chat_view_focus_toggled (chat->view, gtk_widget_has_focus (widget));
1947 }
1948
1949 static void
1950 chat_insert_smiley_activate_cb (EmpathySmileyManager *manager,
1951                                 EmpathySmiley        *smiley,
1952                                 gpointer              user_data)
1953 {
1954         EmpathyChat   *chat = EMPATHY_CHAT (user_data);
1955         GtkTextBuffer *buffer;
1956         GtkTextIter    iter;
1957
1958         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1959
1960         gtk_text_buffer_get_end_iter (buffer, &iter);
1961         gtk_text_buffer_insert (buffer, &iter, smiley->str, -1);
1962
1963         gtk_text_buffer_get_end_iter (buffer, &iter);
1964         gtk_text_buffer_insert (buffer, &iter, " ", -1);
1965 }
1966
1967 typedef struct {
1968         EmpathyChat  *chat;
1969         gchar       *word;
1970
1971         GtkTextIter  start;
1972         GtkTextIter  end;
1973 } EmpathyChatSpell;
1974
1975 static EmpathyChatSpell *
1976 chat_spell_new (EmpathyChat  *chat,
1977                 const gchar *word,
1978                 GtkTextIter  start,
1979                 GtkTextIter  end)
1980 {
1981         EmpathyChatSpell *chat_spell;
1982
1983         chat_spell = g_slice_new0 (EmpathyChatSpell);
1984
1985         chat_spell->chat = g_object_ref (chat);
1986         chat_spell->word = g_strdup (word);
1987         chat_spell->start = start;
1988         chat_spell->end = end;
1989
1990         return chat_spell;
1991 }
1992
1993 static void
1994 chat_spell_free (EmpathyChatSpell *chat_spell)
1995 {
1996         g_object_unref (chat_spell->chat);
1997         g_free (chat_spell->word);
1998         g_slice_free (EmpathyChatSpell, chat_spell);
1999 }
2000
2001 static void
2002 chat_spelling_menu_activate_cb (GtkMenuItem     *menu_item,
2003                                                 EmpathyChatSpell *chat_spell)
2004 {
2005     empathy_chat_correct_word (chat_spell->chat,
2006                                &(chat_spell->start),
2007                                &(chat_spell->end),
2008                                gtk_menu_item_get_label (menu_item));
2009 }
2010
2011
2012 static GtkWidget *
2013 chat_spelling_build_suggestions_menu (const gchar *code,
2014                                       EmpathyChatSpell *chat_spell)
2015 {
2016         GList     *suggestions, *l;
2017         GtkWidget *menu, *menu_item;
2018
2019         suggestions = empathy_spell_get_suggestions (code, chat_spell->word);
2020         if (suggestions == NULL)
2021                 return NULL;
2022
2023         menu = gtk_menu_new ();
2024         for (l = suggestions; l; l = l->next) {
2025                 menu_item = gtk_menu_item_new_with_label (l->data);
2026                 g_signal_connect (G_OBJECT (menu_item), "activate",
2027                                   G_CALLBACK (chat_spelling_menu_activate_cb),
2028                                   chat_spell);
2029                 gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
2030         }
2031         empathy_spell_free_suggestions (suggestions);
2032
2033         gtk_widget_show_all (menu);
2034
2035         return menu;
2036 }
2037
2038 static GtkWidget *
2039 chat_spelling_build_menu (EmpathyChatSpell *chat_spell)
2040 {
2041         GtkWidget *menu, *submenu, *item;
2042         GList     *codes, *l;
2043
2044         codes = empathy_spell_get_enabled_language_codes ();
2045         g_assert (codes != NULL);
2046
2047         if (g_list_length (codes) > 1) {
2048                 menu = gtk_menu_new ();
2049
2050                 for (l = codes; l; l = l->next) {
2051                         const gchar *code, *name;
2052
2053                         code = l->data;
2054                         name = empathy_spell_get_language_name (code);
2055                         if (!name)
2056                                 continue;
2057
2058                         item = gtk_image_menu_item_new_with_label (name);
2059
2060                         submenu = chat_spelling_build_suggestions_menu (
2061                                         code, chat_spell);
2062                         if (submenu == NULL)
2063                                 gtk_widget_set_sensitive (item, FALSE);
2064                         else
2065                                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item),
2066                                                            submenu);
2067                         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2068                 }
2069         } else {
2070                 menu = chat_spelling_build_suggestions_menu (codes->data,
2071                                                              chat_spell);
2072                 if (menu == NULL) {
2073                         menu = gtk_menu_new ();
2074                         item = gtk_menu_item_new_with_label (_("(No Suggestions)"));
2075                         gtk_widget_set_sensitive (item, FALSE);
2076                         gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
2077                 }
2078         }
2079         g_list_free (codes);
2080
2081         gtk_widget_show_all (menu);
2082
2083         return menu;
2084 }
2085
2086 typedef struct {
2087         EmpathyChat  *chat;
2088         gchar        *word;
2089         gchar        *code;
2090 } EmpathyChatWord;
2091
2092 static EmpathyChatWord *
2093 chat_word_new (EmpathyChat  *chat,
2094                 const gchar  *word,
2095                 const gchar  *code)
2096 {
2097         EmpathyChatWord *chat_word;
2098
2099         chat_word = g_slice_new0 (EmpathyChatWord);
2100
2101         chat_word->chat = g_object_ref (chat);
2102         chat_word->word = g_strdup (word);
2103         chat_word->code = g_strdup (code);
2104
2105         return chat_word;
2106 }
2107
2108 static void
2109 chat_word_free (EmpathyChatWord *chat_word)
2110 {
2111         g_object_unref (chat_word->chat);
2112         g_free (chat_word->word);
2113         g_free (chat_word->code);
2114         g_slice_free (EmpathyChatWord, chat_word);
2115 }
2116
2117 static void
2118 chat_add_to_dictionary_activate_cb (GtkMenuItem     *menu_item,
2119                                     EmpathyChatWord *chat_word)
2120 {
2121         EmpathyChatPriv *priv = GET_PRIV (chat_word->chat);
2122
2123         empathy_spell_add_to_dictionary (chat_word->code,
2124                                          chat_word->word);
2125         priv->update_misspelled_words_id =
2126                 g_idle_add (update_misspelled_words, chat_word->chat);
2127 }
2128
2129 static GtkWidget *
2130 chat_spelling_build_add_to_dictionary_item (EmpathyChatSpell *chat_spell)
2131 {
2132         GtkWidget       *menu, *item, *lang_item, *image;
2133         GList           *codes, *l;
2134         gchar           *label;
2135         const gchar     *code, *name;
2136         EmpathyChatWord *chat_word;
2137
2138         codes = empathy_spell_get_enabled_language_codes ();
2139         g_assert (codes != NULL);
2140         if (g_list_length (codes) > 1) {
2141                 /* translators: %s is the selected word */
2142                 label = g_strdup_printf (_("Add '%s' to Dictionary"),
2143                                         chat_spell->word);
2144                 item = gtk_image_menu_item_new_with_mnemonic (label);
2145                 g_free (label);
2146                 image = gtk_image_new_from_icon_name (GTK_STOCK_ADD,
2147                                                       GTK_ICON_SIZE_MENU);
2148                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item),
2149                                                image);
2150
2151                 menu = gtk_menu_new ();
2152
2153                 for (l = codes; l; l = l->next) {
2154                         code = l->data;
2155                         name = empathy_spell_get_language_name (code);
2156                         if (name == NULL)
2157                                 continue;
2158
2159                         lang_item = gtk_image_menu_item_new_with_label (name);
2160
2161                         chat_word= chat_word_new (chat_spell->chat,
2162                                                   chat_spell->word, code);
2163                         g_object_set_data_full (G_OBJECT (lang_item),
2164                                 "chat-word", chat_word,
2165                                 (GDestroyNotify) chat_word_free);
2166
2167                         g_signal_connect (G_OBJECT (lang_item), "activate",
2168                                 G_CALLBACK (chat_add_to_dictionary_activate_cb),
2169                                 chat_word);
2170                         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), lang_item);
2171                 }
2172                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), menu);
2173         } else {
2174                 code = codes->data;
2175                 name = empathy_spell_get_language_name (code);
2176                 g_assert (name != NULL);
2177                 /* translators: first %s is the selected word,
2178                  * second %s is the language name of the target dictionary */
2179                 label = g_strdup_printf (_("Add '%s' to %s Dictionary"),
2180                                         chat_spell->word, name);
2181                 item = gtk_image_menu_item_new_with_mnemonic (label);
2182                 g_free (label);
2183                 image = gtk_image_new_from_icon_name (GTK_STOCK_ADD,
2184                                                       GTK_ICON_SIZE_MENU);
2185                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
2186
2187                 chat_word = chat_word_new (chat_spell->chat, chat_spell->word,
2188                                            code);
2189                 g_object_set_data_full (G_OBJECT (item), "chat-word", chat_word,
2190                                         (GDestroyNotify) chat_word_free);
2191
2192                 g_signal_connect (G_OBJECT (item), "activate",
2193                                   G_CALLBACK (chat_add_to_dictionary_activate_cb),
2194                                   chat_word);
2195         }
2196         g_list_free (codes);
2197
2198         gtk_widget_show_all (item);
2199
2200         return item;
2201 }
2202
2203 static void
2204 chat_text_send_cb (GtkMenuItem *menuitem,
2205                    EmpathyChat *chat)
2206 {
2207         chat_input_text_view_send (chat);
2208 }
2209
2210 static gboolean
2211 chat_input_button_press_event_cb (GtkTextView    *view,
2212                                   GdkEventButton *event,
2213                                   EmpathyChat    *chat)
2214 {
2215         EmpathyChatPriv *priv = GET_PRIV (chat);
2216
2217         priv->most_recent_event_type = event->type;
2218
2219         return FALSE;
2220 }
2221
2222 static void
2223 chat_input_populate_popup_cb (GtkTextView *view,
2224                               GtkMenu     *menu,
2225                               EmpathyChat *chat)
2226 {
2227         EmpathyChatPriv      *priv = GET_PRIV (chat);
2228         GtkTextBuffer        *buffer;
2229         GtkTextTagTable      *table;
2230         GtkTextTag           *tag;
2231         gint                  x, y;
2232         GtkTextIter           iter, start, end;
2233         GtkWidget            *item;
2234         gchar                *str = NULL;
2235         EmpathyChatSpell     *chat_spell;
2236         GtkWidget            *spell_menu;
2237         GtkWidget            *spell_item;
2238         EmpathySmileyManager *smiley_manager;
2239         GtkWidget            *smiley_menu;
2240         GtkWidget            *image;
2241
2242         buffer = gtk_text_view_get_buffer (view);
2243
2244         /* Add the emoticon menu. */
2245         item = gtk_separator_menu_item_new ();
2246         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2247         gtk_widget_show (item);
2248
2249         item = gtk_image_menu_item_new_with_mnemonic (_("Insert Smiley"));
2250         image = gtk_image_new_from_icon_name ("face-smile",
2251                                               GTK_ICON_SIZE_MENU);
2252         gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
2253         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2254         gtk_widget_show (item);
2255
2256         smiley_manager = empathy_smiley_manager_dup_singleton ();
2257         smiley_menu = empathy_smiley_menu_new (smiley_manager,
2258                                                chat_insert_smiley_activate_cb,
2259                                                chat);
2260         gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), smiley_menu);
2261         g_object_unref (smiley_manager);
2262
2263         /* Add the Send menu item. */
2264         gtk_text_buffer_get_bounds (buffer, &start, &end);
2265         str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
2266         if (!EMP_STR_EMPTY (str)) {
2267                 item = gtk_menu_item_new_with_mnemonic (_("_Send"));
2268                 g_signal_connect (G_OBJECT (item), "activate",
2269                                   G_CALLBACK (chat_text_send_cb), chat);
2270                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2271                 gtk_widget_show (item);
2272         }
2273         str = NULL;
2274
2275         /* Add the spell check menu item. */
2276         table = gtk_text_buffer_get_tag_table (buffer);
2277         tag = gtk_text_tag_table_lookup (table, "misspelled");
2278
2279         switch (priv->most_recent_event_type) {
2280             case GDK_BUTTON_PRESS:
2281                 /* get the location from the pointer */
2282                 gtk_widget_get_pointer (GTK_WIDGET (view), &x, &y);
2283                 gtk_text_view_window_to_buffer_coords (GTK_TEXT_VIEW (view),
2284                                                        GTK_TEXT_WINDOW_WIDGET,
2285                                                        x, y,
2286                                                        &x, &y);
2287                 gtk_text_view_get_iter_at_location (GTK_TEXT_VIEW (view),
2288                                                     &iter, x, y);
2289                 break;
2290
2291             default:
2292                 g_warn_if_reached ();
2293                 /* assume the KEY_PRESS case */
2294
2295             case GDK_KEY_PRESS:
2296                 /* get the location from the cursor */
2297                 gtk_text_buffer_get_iter_at_mark (buffer, &iter,
2298                                 gtk_text_buffer_get_insert (buffer));
2299                 break;
2300
2301         }
2302
2303         start = end = iter;
2304         if (gtk_text_iter_backward_to_tag_toggle (&start, tag) &&
2305             gtk_text_iter_forward_to_tag_toggle (&end, tag)) {
2306
2307                 str = gtk_text_buffer_get_text (buffer,
2308                                                 &start, &end, FALSE);
2309         }
2310         if (!EMP_STR_EMPTY (str)) {
2311                 chat_spell = chat_spell_new (chat, str, start, end);
2312                 g_object_set_data_full (G_OBJECT (menu),
2313                                         "chat-spell", chat_spell,
2314                                         (GDestroyNotify) chat_spell_free);
2315
2316                 item = gtk_separator_menu_item_new ();
2317                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2318                 gtk_widget_show (item);
2319
2320                 /* Spelling suggestions */
2321                 item = gtk_image_menu_item_new_with_mnemonic (_("_Spelling Suggestions"));
2322                 image = gtk_image_new_from_icon_name (GTK_STOCK_SPELL_CHECK,
2323                                                       GTK_ICON_SIZE_MENU);
2324                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
2325
2326                 spell_menu = chat_spelling_build_menu (chat_spell);
2327                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), spell_menu);
2328
2329
2330                 spell_item = gtk_separator_menu_item_new ();
2331                 gtk_menu_shell_append (GTK_MENU_SHELL (spell_menu), spell_item);
2332                 gtk_widget_show (spell_item);
2333
2334                 /* Add to dictionary */
2335                 spell_item = chat_spelling_build_add_to_dictionary_item (chat_spell);
2336
2337                 gtk_menu_shell_append (GTK_MENU_SHELL (spell_menu), spell_item);
2338                 gtk_widget_show (spell_item);
2339
2340                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2341                 gtk_widget_show (item);
2342         }
2343 }
2344
2345
2346 static gboolean
2347 chat_log_filter (TplEvent *event,
2348                  gpointer user_data)
2349 {
2350         EmpathyChat *chat = user_data;
2351         EmpathyMessage *message;
2352         EmpathyChatPriv *priv = GET_PRIV (chat);
2353         const GList *pending;
2354
2355         g_return_val_if_fail (TPL_IS_EVENT (event), FALSE);
2356         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
2357
2358         pending = empathy_tp_chat_get_pending_messages (priv->tp_chat);
2359         message = empathy_message_from_tpl_log_event (event);
2360
2361         for (; pending; pending = g_list_next (pending)) {
2362                 if (empathy_message_equal (message, pending->data)) {
2363                         g_object_unref (message);
2364                         return FALSE;
2365                 }
2366         }
2367
2368         g_object_unref (message);
2369         return TRUE;
2370 }
2371
2372
2373 static void
2374 show_pending_messages (EmpathyChat *chat) {
2375         EmpathyChatPriv *priv = GET_PRIV (chat);
2376         const GList *messages, *l;
2377
2378         g_return_if_fail (EMPATHY_IS_CHAT (chat));
2379
2380         if (chat->view == NULL || priv->tp_chat == NULL)
2381                 return;
2382
2383         if (!priv->can_show_pending)
2384                 return;
2385
2386         messages = empathy_tp_chat_get_pending_messages (priv->tp_chat);
2387
2388         for (l = messages; l != NULL ; l = g_list_next (l)) {
2389                 EmpathyMessage *message = EMPATHY_MESSAGE (l->data);
2390                 chat_message_received (chat, message, TRUE);
2391         }
2392 }
2393
2394
2395 static void
2396 got_filtered_messages_cb (GObject *manager,
2397                 GAsyncResult *result,
2398                 gpointer user_data)
2399 {
2400         GList *l;
2401         GList *messages;
2402         EmpathyChat *chat = EMPATHY_CHAT (user_data);
2403         EmpathyChatPriv *priv = GET_PRIV (chat);
2404         GError *error = NULL;
2405
2406         if (!tpl_log_manager_get_filtered_events_finish (TPL_LOG_MANAGER (manager),
2407                 result, &messages, &error)) {
2408                 DEBUG ("%s. Aborting.", error->message);
2409                 empathy_chat_view_append_event (chat->view,
2410                         _("Failed to retrieve recent logs"));
2411                 g_error_free (error);
2412                 goto out;
2413         }
2414
2415         for (l = messages; l; l = g_list_next (l)) {
2416                 EmpathyMessage *message;
2417
2418                 g_assert (TPL_IS_EVENT (l->data));
2419
2420                 message = empathy_message_from_tpl_log_event (l->data);
2421                 g_object_unref (l->data);
2422
2423                 if (empathy_message_is_edit (message)) {
2424                         /* this is an edited message, create a synthetic event
2425                          * using the supersedes token and
2426                          * original-message-sent timestamp, that we can then
2427                          * replace */
2428                         EmpathyMessage *syn_msg = g_object_new (
2429                                 EMPATHY_TYPE_MESSAGE,
2430                                 "body", "",
2431                                 "token", empathy_message_get_supersedes (message),
2432                                 "type", empathy_message_get_tptype (message),
2433                                 "timestamp", empathy_message_get_original_timestamp (message),
2434                                 "incoming", empathy_message_is_incoming (message),
2435                                 "is-backlog", TRUE,
2436                                 "receiver", empathy_message_get_receiver (message),
2437                                 "sender", empathy_message_get_sender (message),
2438                                 NULL);
2439
2440                         empathy_chat_view_append_message (chat->view, syn_msg);
2441                         empathy_chat_view_edit_message (chat->view, message);
2442
2443                         g_object_unref (syn_msg);
2444                 } else {
2445                         /* append the latest message */
2446                         empathy_chat_view_append_message (chat->view, message);
2447                 }
2448
2449                 g_object_unref (message);
2450         }
2451         g_list_free (messages);
2452
2453 out:
2454         /* in case of TPL error, skip backlog and show pending messages */
2455         priv->can_show_pending = TRUE;
2456         show_pending_messages (chat);
2457
2458         /* FIXME: See Bug#610994, we are forcing the ACK of the queue. See comments
2459          * about it in EmpathyChatPriv definition */
2460         priv->retrieving_backlogs = FALSE;
2461         empathy_chat_messages_read (chat);
2462
2463         /* Turn back on scrolling */
2464         empathy_chat_view_scroll (chat->view, TRUE);
2465 }
2466
2467 static void
2468 chat_add_logs (EmpathyChat *chat)
2469 {
2470         EmpathyChatPriv *priv = GET_PRIV (chat);
2471         TplEntity       *target;
2472
2473         if (!priv->id) {
2474                 return;
2475         }
2476
2477         /* Turn off scrolling temporarily */
2478         empathy_chat_view_scroll (chat->view, FALSE);
2479
2480         /* Add messages from last conversation */
2481         if (priv->handle_type == TP_HANDLE_TYPE_ROOM)
2482           target = tpl_entity_new_from_room_id (priv->id);
2483         else
2484           target = tpl_entity_new (priv->id, TPL_ENTITY_CONTACT, NULL, NULL);
2485
2486         priv->retrieving_backlogs = TRUE;
2487         tpl_log_manager_get_filtered_events_async (priv->log_manager,
2488                                                    priv->account,
2489                                                    target,
2490                                                    TPL_EVENT_MASK_TEXT,
2491                                                    5,
2492                                                    chat_log_filter,
2493                                                    chat,
2494                                                    got_filtered_messages_cb,
2495                                                    (gpointer) chat);
2496
2497         g_object_unref (target);
2498 }
2499
2500 static gint
2501 chat_contacts_completion_func (const gchar *s1,
2502                                const gchar *s2,
2503                                gsize        n)
2504 {
2505         gchar *tmp, *nick1, *nick2;
2506         gint   ret;
2507
2508         if (s1 == s2) {
2509                 return 0;
2510         }
2511         if (!s1 || !s2) {
2512                 return s1 ? -1 : +1;
2513         }
2514
2515         tmp = g_utf8_normalize (s1, -1, G_NORMALIZE_DEFAULT);
2516         nick1 = g_utf8_casefold (tmp, -1);
2517         g_free (tmp);
2518
2519         tmp = g_utf8_normalize (s2, -1, G_NORMALIZE_DEFAULT);
2520         nick2 = g_utf8_casefold (tmp, -1);
2521         g_free (tmp);
2522
2523         ret = strncmp (nick1, nick2, n);
2524
2525         g_free (nick1);
2526         g_free (nick2);
2527
2528         return ret;
2529 }
2530
2531 static gchar *
2532 build_part_message (guint           reason,
2533                     const gchar    *name,
2534                     EmpathyContact *actor,
2535                     const gchar    *message)
2536 {
2537         GString *s = g_string_new ("");
2538         const gchar *actor_name = NULL;
2539
2540         if (actor != NULL) {
2541                 actor_name = empathy_contact_get_alias (actor);
2542         }
2543
2544         /* Having an actor only really makes sense for a few actions... */
2545         switch (reason) {
2546         case TP_CHANNEL_GROUP_CHANGE_REASON_OFFLINE:
2547                 g_string_append_printf (s, _("%s has disconnected"), name);
2548                 break;
2549         case TP_CHANNEL_GROUP_CHANGE_REASON_KICKED:
2550                 if (actor_name != NULL) {
2551                         /* translators: reverse the order of these arguments
2552                          * if the kicked should come before the kicker in your locale.
2553                          */
2554                         g_string_append_printf (s, _("%1$s was kicked by %2$s"),
2555                                 name, actor_name);
2556                 } else {
2557                         g_string_append_printf (s, _("%s was kicked"), name);
2558                 }
2559                 break;
2560         case TP_CHANNEL_GROUP_CHANGE_REASON_BANNED:
2561                 if (actor_name != NULL) {
2562                         /* translators: reverse the order of these arguments
2563                          * if the banned should come before the banner in your locale.
2564                          */
2565                         g_string_append_printf (s, _("%1$s was banned by %2$s"),
2566                                 name, actor_name);
2567                 } else {
2568                         g_string_append_printf (s, _("%s was banned"), name);
2569                 }
2570                 break;
2571         default:
2572                 g_string_append_printf (s, _("%s has left the room"), name);
2573         }
2574
2575         if (!EMP_STR_EMPTY (message)) {
2576                 /* Note to translators: this string is appended to
2577                  * notifications like "foo has left the room", with the message
2578                  * given by the user living the room. If this poses a problem,
2579                  * please let us know. :-)
2580                  */
2581                 g_string_append_printf (s, _(" (%s)"), message);
2582         }
2583
2584         return g_string_free (s, FALSE);
2585 }
2586
2587 static void
2588 chat_members_changed_cb (EmpathyTpChat  *tp_chat,
2589                          EmpathyContact *contact,
2590                          EmpathyContact *actor,
2591                          guint           reason,
2592                          gchar          *message,
2593                          gboolean        is_member,
2594                          EmpathyChat    *chat)
2595 {
2596         EmpathyChatPriv *priv = GET_PRIV (chat);
2597         const gchar *name = empathy_contact_get_alias (contact);
2598         gchar *str;
2599
2600         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED != reason);
2601
2602         if (priv->block_events_timeout_id != 0)
2603                 return;
2604
2605         if (is_member) {
2606                 str = g_strdup_printf (_("%s has joined the room"),
2607                                        name);
2608         } else {
2609                 str = build_part_message (reason, name, actor, message);
2610         }
2611
2612         empathy_chat_view_append_event (chat->view, str);
2613         g_free (str);
2614 }
2615
2616 static void
2617 chat_member_renamed_cb (EmpathyTpChat  *tp_chat,
2618                          EmpathyContact *old_contact,
2619                          EmpathyContact *new_contact,
2620                          guint           reason,
2621                          gchar          *message,
2622                          EmpathyChat    *chat)
2623 {
2624         EmpathyChatPriv *priv = GET_PRIV (chat);
2625
2626         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED == reason);
2627
2628         if (priv->block_events_timeout_id == 0) {
2629                 gchar *str;
2630
2631                 str = g_strdup_printf (_("%s is now known as %s"),
2632                                        empathy_contact_get_alias (old_contact),
2633                                        empathy_contact_get_alias (new_contact));
2634                 empathy_chat_view_append_event (chat->view, str);
2635                 g_free (str);
2636         }
2637
2638 }
2639
2640 static gboolean
2641 chat_contacts_visible_timeout_cb (gpointer chat)
2642 {
2643         EmpathyChatPriv *priv = GET_PRIV (chat);
2644
2645         /* Relax the size request */
2646         gtk_widget_set_size_request (priv->vbox_left, -1, -1);
2647
2648         /* Set the position of the slider. This must be done here because
2649          * GtkPaned need to know its size allocation and it will be settled only
2650          * after the gtk_window_resize () tough effect. */
2651         if (priv->contacts_width > 0) {
2652                 gtk_paned_set_position (GTK_PANED (priv->hpaned),
2653                                         priv->contacts_width);
2654         }
2655
2656         priv->contacts_visible_id = 0;
2657
2658         return FALSE;
2659 }
2660
2661 static void
2662 chat_update_contacts_visibility (EmpathyChat *chat,
2663                          gboolean show)
2664 {
2665         EmpathyChatPriv *priv = GET_PRIV (chat);
2666
2667         if (!priv->scrolled_window_contacts) {
2668                 return;
2669         }
2670
2671         if (priv->remote_contact != NULL) {
2672                 show = FALSE;
2673         }
2674
2675         if (show && priv->contact_list_view == NULL) {
2676                 EmpathyContactListStore *store;
2677                 gint                     min_width;
2678                 GtkAllocation            allocation;
2679
2680                 /* We are adding the contact list to the chat, we don't want the
2681                  * chat view to become too small. If the chat view is already
2682                  * smaller than 250 make sure that size won't change. If the
2683                  * chat view is bigger the contact list will take some space on
2684                  * it but we make sure the chat view don't become smaller than
2685                  * 250. Relax the size request once the resize is done */
2686                 gtk_widget_get_allocation (priv->vbox_left, &allocation);
2687                 min_width = MIN (allocation.width, 250);
2688                 gtk_widget_set_size_request (priv->vbox_left, min_width, -1);
2689
2690                 /* There is no way to know when the window resize will happen
2691                  * since it is WM's decision. Let's hope it won't be longer. */
2692                 if (priv->contacts_visible_id != 0)
2693                         g_source_remove (priv->contacts_visible_id);
2694                 priv->contacts_visible_id = g_timeout_add (500,
2695                         chat_contacts_visible_timeout_cb, chat);
2696
2697                 store = empathy_contact_list_store_new (
2698                                 EMPATHY_CONTACT_LIST (priv->tp_chat));
2699                 empathy_contact_list_store_set_show_groups (
2700                                 EMPATHY_CONTACT_LIST_STORE (store), FALSE);
2701
2702                 priv->contact_list_view = GTK_WIDGET (empathy_contact_list_view_new (store,
2703                         EMPATHY_CONTACT_LIST_FEATURE_CONTACT_TOOLTIP,
2704                         EMPATHY_CONTACT_FEATURE_CHAT |
2705                         EMPATHY_CONTACT_FEATURE_CALL |
2706                         EMPATHY_CONTACT_FEATURE_LOG |
2707                         EMPATHY_CONTACT_FEATURE_INFO));
2708                 gtk_container_add (GTK_CONTAINER (priv->scrolled_window_contacts),
2709                                    priv->contact_list_view);
2710                 gtk_widget_show (priv->contact_list_view);
2711                 gtk_widget_show (priv->scrolled_window_contacts);
2712                 g_object_unref (store);
2713         } else if (!show) {
2714                 priv->contacts_width = gtk_paned_get_position (GTK_PANED (priv->hpaned));
2715                 gtk_widget_hide (priv->scrolled_window_contacts);
2716                 if (priv->contact_list_view != NULL) {
2717                         gtk_widget_destroy (priv->contact_list_view);
2718                         priv->contact_list_view = NULL;
2719                 }
2720         }
2721 }
2722
2723 void
2724 empathy_chat_set_show_contacts (EmpathyChat *chat,
2725                                 gboolean     show)
2726 {
2727         EmpathyChatPriv *priv = GET_PRIV (chat);
2728
2729         priv->show_contacts = show;
2730
2731         chat_update_contacts_visibility (chat, show);
2732
2733         g_object_notify (G_OBJECT (chat), "show-contacts");
2734 }
2735
2736 static void
2737 chat_remote_contact_changed_cb (EmpathyChat *chat)
2738 {
2739         EmpathyChatPriv *priv = GET_PRIV (chat);
2740
2741         if (priv->remote_contact != NULL) {
2742                 g_object_unref (priv->remote_contact);
2743                 priv->remote_contact = NULL;
2744         }
2745
2746         g_free (priv->id);
2747
2748         priv->id = g_strdup (empathy_tp_chat_get_id (priv->tp_chat));
2749         priv->remote_contact = empathy_tp_chat_get_remote_contact (priv->tp_chat);
2750         if (priv->remote_contact != NULL) {
2751                 g_object_ref (priv->remote_contact);
2752                 priv->handle_type = TP_HANDLE_TYPE_CONTACT;
2753         }
2754         else if (priv->tp_chat != NULL) {
2755                 tp_channel_get_handle ((TpChannel *) priv->tp_chat, &priv->handle_type);
2756         }
2757
2758         chat_update_contacts_visibility (chat, priv->show_contacts);
2759
2760         g_object_notify (G_OBJECT (chat), "remote-contact");
2761         g_object_notify (G_OBJECT (chat), "id");
2762 }
2763
2764 static void
2765 chat_invalidated_cb (EmpathyTpChat *tp_chat,
2766                  guint domain,
2767                  gint code,
2768                  gchar *message,
2769                  EmpathyChat   *chat)
2770 {
2771         EmpathyChatPriv *priv;
2772
2773         priv = GET_PRIV (chat);
2774
2775         if (!priv->tp_chat) {
2776                 return;
2777         }
2778
2779         chat_composing_remove_timeout (chat);
2780         g_object_unref (priv->tp_chat);
2781         priv->tp_chat = NULL;
2782         g_object_notify (G_OBJECT (chat), "tp-chat");
2783
2784         empathy_chat_view_append_event (chat->view, _("Disconnected"));
2785         gtk_widget_set_sensitive (chat->input_text_view, FALSE);
2786
2787         chat_update_contacts_visibility (chat, FALSE);
2788
2789         priv->unread_messages_when_offline = priv->unread_messages;
2790 }
2791
2792 static gboolean
2793 update_misspelled_words (gpointer data)
2794 {
2795         EmpathyChat *chat = EMPATHY_CHAT (data);
2796         EmpathyChatPriv *priv = GET_PRIV (chat);
2797         GtkTextBuffer *buffer;
2798         GtkTextIter iter;
2799         gint length;
2800
2801         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2802
2803         gtk_text_buffer_get_end_iter (buffer, &iter);
2804         length = gtk_text_iter_get_offset (&iter);
2805         chat_input_text_buffer_insert_text_cb (buffer, &iter,
2806                                                NULL, length, chat);
2807
2808         priv->update_misspelled_words_id = 0;
2809
2810         return FALSE;
2811 }
2812
2813 static void
2814 conf_spell_checking_cb (GSettings *gsettings_chat,
2815                         const gchar *key,
2816                         gpointer user_data)
2817 {
2818         EmpathyChat *chat = EMPATHY_CHAT (user_data);
2819         EmpathyChatPriv *priv = GET_PRIV (chat);
2820         gboolean spell_checker;
2821         GtkTextBuffer *buffer;
2822
2823         if (strcmp (key, EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED) != 0)
2824                 return;
2825
2826         spell_checker = g_settings_get_boolean (gsettings_chat,
2827                         EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED);
2828
2829         if (!empathy_spell_supported ()) {
2830                 spell_checker = FALSE;
2831         }
2832
2833         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2834
2835         if (spell_checker == priv->spell_checking_enabled) {
2836                 if (spell_checker) {
2837                         /* Possibly changed dictionaries,
2838                          * update misspelled words. Need to do so in idle
2839                          * so the spell checker is updated. */
2840                         priv->update_misspelled_words_id =
2841                                 g_idle_add (update_misspelled_words, chat);
2842                 }
2843
2844                 return;
2845         }
2846
2847         if (spell_checker) {
2848                 GtkTextIter iter;
2849
2850                 priv->notify_cursor_position_id = tp_g_signal_connect_object  (
2851                                 buffer, "notify::cursor-position",
2852                                 G_CALLBACK (chat_input_text_buffer_notify_cursor_position_cb),
2853                                 chat, 0);
2854                 priv->insert_text_id = tp_g_signal_connect_object  (
2855                                 buffer, "insert-text",
2856                                 G_CALLBACK (chat_input_text_buffer_insert_text_cb),
2857                                 chat, G_CONNECT_AFTER);
2858                 priv->delete_range_id = tp_g_signal_connect_object  (
2859                                 buffer, "delete-range",
2860                                 G_CALLBACK (chat_input_text_buffer_delete_range_cb),
2861                                 chat, G_CONNECT_AFTER);
2862
2863                 gtk_text_buffer_create_tag (buffer, "misspelled",
2864                                             "underline", PANGO_UNDERLINE_ERROR,
2865                                             NULL);
2866
2867                 gtk_text_buffer_get_iter_at_mark (buffer, &iter,
2868                                                   gtk_text_buffer_get_insert (buffer));
2869                 gtk_text_buffer_create_mark (buffer, "previous-cursor-position",
2870                                              &iter, TRUE);
2871
2872                 /* Mark misspelled words in the existing buffer.
2873                  * Need to do so in idle so the spell checker is updated. */
2874                 priv->update_misspelled_words_id =
2875                         g_idle_add (update_misspelled_words, chat);
2876         } else {
2877                 GtkTextTagTable *table;
2878                 GtkTextTag *tag;
2879
2880                 g_signal_handler_disconnect (buffer, priv->notify_cursor_position_id);
2881                 priv->notify_cursor_position_id = 0;
2882                 g_signal_handler_disconnect (buffer, priv->insert_text_id);
2883                 priv->insert_text_id = 0;
2884                 g_signal_handler_disconnect (buffer, priv->delete_range_id);
2885                 priv->delete_range_id = 0;
2886
2887                 table = gtk_text_buffer_get_tag_table (buffer);
2888                 tag = gtk_text_tag_table_lookup (table, "misspelled");
2889                 gtk_text_tag_table_remove (table, tag);
2890
2891                 gtk_text_buffer_delete_mark_by_name (buffer,
2892                                                      "previous-cursor-position");
2893         }
2894
2895         priv->spell_checking_enabled = spell_checker;
2896 }
2897
2898 static gboolean
2899 save_paned_pos_timeout (gpointer data)
2900 {
2901         EmpathyChat *self = data;
2902         gint hpaned_pos;
2903
2904         hpaned_pos = gtk_paned_get_position (GTK_PANED (self->priv->hpaned));
2905
2906         g_settings_set_int (self->priv->gsettings_ui,
2907                             EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS,
2908                             hpaned_pos);
2909
2910         return FALSE;
2911 }
2912
2913 static gboolean
2914 chat_hpaned_pos_changed_cb (GtkWidget* hpaned,
2915                 GParamSpec *spec,
2916                 gpointer user_data)
2917 {
2918         EmpathyChat *chat = EMPATHY_CHAT (user_data);
2919
2920         if (chat->priv->save_paned_pos_id != 0)
2921                 g_source_remove (chat->priv->save_paned_pos_id);
2922
2923         chat->priv->save_paned_pos_id = g_timeout_add_seconds (1,
2924                 save_paned_pos_timeout, chat);
2925
2926         return TRUE;
2927 }
2928
2929 static void
2930 chat_create_ui (EmpathyChat *chat)
2931 {
2932         EmpathyChatPriv *priv = GET_PRIV (chat);
2933         GtkBuilder      *gui;
2934         GList           *list = NULL;
2935         gchar           *filename;
2936         GtkTextBuffer   *buffer;
2937         EmpathyThemeManager *theme_mgr;
2938
2939         filename = empathy_file_lookup ("empathy-chat.ui",
2940                                         "libempathy-gtk");
2941         gui = empathy_builder_get_file (filename,
2942                                         "chat_widget", &priv->widget,
2943                                         "hpaned", &priv->hpaned,
2944                                         "vbox_left", &priv->vbox_left,
2945                                         "scrolled_window_chat", &priv->scrolled_window_chat,
2946                                         "scrolled_window_input", &priv->scrolled_window_input,
2947                                         "hbox_topic", &priv->hbox_topic,
2948                                         "expander_topic", &priv->expander_topic,
2949                                         "label_topic", &priv->label_topic,
2950                                         "scrolled_window_contacts", &priv->scrolled_window_contacts,
2951                                         "info_bar_vbox", &priv->info_bar_vbox,
2952                                         NULL);
2953
2954         empathy_builder_connect (gui, chat,
2955                 "expander_topic", "notify::expanded", chat_topic_expander_activate_cb,
2956                 "label_topic", "size-allocate", chat_topic_label_size_allocate_cb,
2957                 NULL);
2958
2959         g_free (filename);
2960
2961         /* Add message view. */
2962         theme_mgr = empathy_theme_manager_dup_singleton ();
2963         chat->view = empathy_theme_manager_create_view (theme_mgr);
2964         g_object_unref (theme_mgr);
2965         /* If this is a GtkTextView, it's set as a drag destination for text/plain
2966            and other types, even though it's non-editable and doesn't accept any
2967            drags.  This steals drag motion for anything inside the scrollbars,
2968            making drag destinations on chat windows far less useful.
2969          */
2970         gtk_drag_dest_unset (GTK_WIDGET (chat->view));
2971         g_signal_connect (chat->view, "focus_in_event",
2972                           G_CALLBACK (chat_text_view_focus_in_event_cb),
2973                           chat);
2974         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_chat),
2975                            GTK_WIDGET (chat->view));
2976         gtk_widget_show (GTK_WIDGET (chat->view));
2977
2978         /* Add input GtkTextView */
2979         chat->input_text_view = empathy_input_text_view_new ();
2980         g_signal_connect (chat->input_text_view, "notify::has-focus",
2981                           G_CALLBACK (chat_input_has_focus_notify_cb),
2982                           chat);
2983         g_signal_connect (chat->input_text_view, "key-press-event",
2984                           G_CALLBACK (chat_input_key_press_event_cb),
2985                           chat);
2986         g_signal_connect (chat->input_text_view, "realize",
2987                           G_CALLBACK (chat_input_realize_cb),
2988                           chat);
2989         g_signal_connect (chat->input_text_view, "button-press-event",
2990                           G_CALLBACK (chat_input_button_press_event_cb),
2991                           chat);
2992         g_signal_connect (chat->input_text_view, "populate-popup",
2993                           G_CALLBACK (chat_input_populate_popup_cb),
2994                           chat);
2995         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2996         tp_g_signal_connect_object  (buffer, "changed",
2997                           G_CALLBACK (chat_input_text_buffer_changed_cb),
2998                           chat, 0);
2999         tp_g_signal_connect_object (priv->gsettings_chat,
3000                         "changed::" EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED,
3001                         G_CALLBACK (conf_spell_checking_cb), chat, 0);
3002         conf_spell_checking_cb (priv->gsettings_chat,
3003                                 EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED, chat);
3004         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_input),
3005                            chat->input_text_view);
3006         gtk_widget_show (chat->input_text_view);
3007
3008         /* Add the (invisible) search bar */
3009         priv->search_bar = empathy_search_bar_new (chat->view);
3010         gtk_box_pack_start (GTK_BOX(priv->vbox_left),
3011                             priv->search_bar,
3012                             FALSE, FALSE, 0);
3013         gtk_box_reorder_child (GTK_BOX(priv->vbox_left), priv->search_bar, 1);
3014
3015         /* Initialy hide the topic, will be shown if not empty */
3016         gtk_widget_hide (priv->hbox_topic);
3017
3018         g_signal_connect (priv->hpaned, "notify::position",
3019                           G_CALLBACK (chat_hpaned_pos_changed_cb),
3020                           chat);
3021
3022         /* Set widget focus order */
3023         list = g_list_append (NULL, priv->search_bar);
3024         list = g_list_append (list, priv->scrolled_window_input);
3025         gtk_container_set_focus_chain (GTK_CONTAINER (priv->vbox_left), list);
3026         g_list_free (list);
3027
3028         list = g_list_append (NULL, priv->vbox_left);
3029         list = g_list_append (list, priv->scrolled_window_contacts);
3030         gtk_container_set_focus_chain (GTK_CONTAINER (priv->hpaned), list);
3031         g_list_free (list);
3032
3033         list = g_list_append (NULL, priv->hpaned);
3034         list = g_list_append (list, priv->hbox_topic);
3035         gtk_container_set_focus_chain (GTK_CONTAINER (priv->widget), list);
3036         g_list_free (list);
3037
3038         /* Add the main widget in the chat widget */
3039         gtk_box_pack_start (GTK_BOX (chat), priv->widget, TRUE, TRUE, 0);
3040         g_object_unref (gui);
3041 }
3042
3043 static void
3044 chat_finalize (GObject *object)
3045 {
3046         EmpathyChat     *chat;
3047         EmpathyChatPriv *priv;
3048
3049         chat = EMPATHY_CHAT (object);
3050         priv = GET_PRIV (chat);
3051
3052         DEBUG ("Finalized: %p", object);
3053
3054         if (priv->update_misspelled_words_id != 0)
3055                 g_source_remove (priv->update_misspelled_words_id);
3056
3057         if (priv->save_paned_pos_id != 0)
3058                 g_source_remove (priv->save_paned_pos_id);
3059
3060         if (priv->contacts_visible_id != 0)
3061                 g_source_remove (priv->contacts_visible_id);
3062
3063         g_object_unref (priv->gsettings_chat);
3064         g_object_unref (priv->gsettings_ui);
3065
3066         g_list_foreach (priv->input_history, (GFunc) chat_input_history_entry_free, NULL);
3067         g_list_free (priv->input_history);
3068
3069         g_list_foreach (priv->compositors, (GFunc) g_object_unref, NULL);
3070         g_list_free (priv->compositors);
3071
3072         chat_composing_remove_timeout (chat);
3073
3074         g_object_unref (priv->account_manager);
3075         g_object_unref (priv->log_manager);
3076
3077         if (priv->tp_chat) {
3078                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3079                         chat_invalidated_cb, chat);
3080                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3081                         chat_message_received_cb, chat);
3082                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3083                         chat_message_acknowledged_cb, chat);
3084                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3085                         chat_send_error_cb, chat);
3086                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3087                         chat_state_changed_cb, chat);
3088                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3089                         chat_property_changed_cb, chat);
3090                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3091                         chat_members_changed_cb, chat);
3092                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3093                         chat_remote_contact_changed_cb, chat);
3094                 empathy_tp_chat_leave (priv->tp_chat, "");
3095                 g_object_unref (priv->tp_chat);
3096         }
3097         if (priv->account) {
3098                 g_object_unref (priv->account);
3099         }
3100         if (priv->remote_contact) {
3101                 g_object_unref (priv->remote_contact);
3102         }
3103
3104         if (priv->block_events_timeout_id) {
3105                 g_source_remove (priv->block_events_timeout_id);
3106         }
3107
3108         g_free (priv->id);
3109         g_free (priv->name);
3110         g_free (priv->subject);
3111         g_completion_free (priv->completion);
3112
3113         G_OBJECT_CLASS (empathy_chat_parent_class)->finalize (object);
3114 }
3115
3116 static void
3117 chat_constructed (GObject *object)
3118 {
3119         EmpathyChat *chat = EMPATHY_CHAT (object);
3120         EmpathyChatPriv *priv = GET_PRIV (chat);
3121
3122         if (priv->handle_type != TP_HANDLE_TYPE_ROOM) {
3123                 /* First display logs from the logger and then display pending messages */
3124                 chat_add_logs (chat);
3125         }
3126          else {
3127                 /* Just display pending messages for rooms */
3128                 priv->can_show_pending = TRUE;
3129                 show_pending_messages (chat);
3130         }
3131 }
3132
3133 static void
3134 empathy_chat_class_init (EmpathyChatClass *klass)
3135 {
3136         GObjectClass   *object_class = G_OBJECT_CLASS (klass);
3137
3138         object_class->finalize = chat_finalize;
3139         object_class->get_property = chat_get_property;
3140         object_class->set_property = chat_set_property;
3141         object_class->constructed = chat_constructed;
3142
3143         g_object_class_install_property (object_class,
3144                                          PROP_TP_CHAT,
3145                                          g_param_spec_object ("tp-chat",
3146                                                               "Empathy tp chat",
3147                                                               "The tp chat object",
3148                                                               EMPATHY_TYPE_TP_CHAT,
3149                                                               G_PARAM_CONSTRUCT |
3150                                                               G_PARAM_READWRITE |
3151                                                               G_PARAM_STATIC_STRINGS));
3152         g_object_class_install_property (object_class,
3153                                          PROP_ACCOUNT,
3154                                          g_param_spec_object ("account",
3155                                                               "Account of the chat",
3156                                                               "The account of the chat",
3157                                                               TP_TYPE_ACCOUNT,
3158                                                               G_PARAM_READABLE |
3159                                                               G_PARAM_STATIC_STRINGS));
3160         g_object_class_install_property (object_class,
3161                                          PROP_ID,
3162                                          g_param_spec_string ("id",
3163                                                               "Chat's id",
3164                                                               "The id of the chat",
3165                                                               NULL,
3166                                                               G_PARAM_READABLE |
3167                                                               G_PARAM_STATIC_STRINGS));
3168         g_object_class_install_property (object_class,
3169                                          PROP_NAME,
3170                                          g_param_spec_string ("name",
3171                                                               "Chat's name",
3172                                                               "The name of the chat",
3173                                                               NULL,
3174                                                               G_PARAM_READABLE |
3175                                                               G_PARAM_STATIC_STRINGS));
3176         g_object_class_install_property (object_class,
3177                                          PROP_SUBJECT,
3178                                          g_param_spec_string ("subject",
3179                                                               "Chat's subject",
3180                                                               "The subject or topic of the chat",
3181                                                               NULL,
3182                                                               G_PARAM_READABLE |
3183                                                               G_PARAM_STATIC_STRINGS));
3184         g_object_class_install_property (object_class,
3185                                          PROP_REMOTE_CONTACT,
3186                                          g_param_spec_object ("remote-contact",
3187                                                               "The remote contact",
3188                                                               "The remote contact is any",
3189                                                               EMPATHY_TYPE_CONTACT,
3190                                                               G_PARAM_READABLE |
3191                                                               G_PARAM_STATIC_STRINGS));
3192         g_object_class_install_property (object_class,
3193                                          PROP_SHOW_CONTACTS,
3194                                          g_param_spec_boolean ("show-contacts",
3195                                                                "Contacts' visibility",
3196                                                                "The visibility of the contacts' list",
3197                                                                TRUE,
3198                                                                G_PARAM_READWRITE |
3199                                                                G_PARAM_STATIC_STRINGS));
3200
3201         g_object_class_install_property (object_class,
3202                                          PROP_SMS_CHANNEL,
3203                                          g_param_spec_boolean ("sms-channel",
3204                                                                "SMS Channel",
3205                                                                "TRUE if this channel is for sending SMSes",
3206                                                                FALSE,
3207                                                                G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
3208
3209         g_object_class_install_property (object_class,
3210                                          PROP_N_MESSAGES_SENDING,
3211                                          g_param_spec_uint ("n-messages-sending",
3212                                                             "Num Messages Sending",
3213                                                             "The number of messages being sent",
3214                                                             0, G_MAXUINT, 0,
3215                                                             G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
3216
3217         g_object_class_install_property (object_class,
3218                                          PROP_NB_UNREAD_MESSAGES,
3219                                          g_param_spec_uint ("nb-unread-messages",
3220                                                             "Num Unread Messages",
3221                                                             "The number of unread messages",
3222                                                             0, G_MAXUINT, 0,
3223                                                             G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
3224
3225         signals[COMPOSING] =
3226                 g_signal_new ("composing",
3227                               G_OBJECT_CLASS_TYPE (object_class),
3228                               G_SIGNAL_RUN_LAST,
3229                               0,
3230                               NULL, NULL,
3231                               g_cclosure_marshal_VOID__BOOLEAN,
3232                               G_TYPE_NONE,
3233                               1, G_TYPE_BOOLEAN);
3234
3235         signals[NEW_MESSAGE] =
3236                 g_signal_new ("new-message",
3237                               G_OBJECT_CLASS_TYPE (object_class),
3238                               G_SIGNAL_RUN_LAST,
3239                               0,
3240                               NULL, NULL,
3241                               _empathy_gtk_marshal_VOID__OBJECT_BOOLEAN,
3242                               G_TYPE_NONE,
3243                               2, EMPATHY_TYPE_MESSAGE, G_TYPE_BOOLEAN);
3244
3245         signals[PART_COMMAND_ENTERED] =
3246                         g_signal_new ("part-command-entered",
3247                                   G_OBJECT_CLASS_TYPE (object_class),
3248                                   G_SIGNAL_RUN_LAST,
3249                                   0,
3250                                   NULL, NULL,
3251                                   g_cclosure_marshal_VOID__POINTER,
3252                                   G_TYPE_NONE,
3253                                   1, G_TYPE_STRV);
3254
3255         g_type_class_add_private (object_class, sizeof (EmpathyChatPriv));
3256 }
3257
3258 static gboolean
3259 chat_block_events_timeout_cb (gpointer data)
3260 {
3261         EmpathyChatPriv *priv = GET_PRIV (data);
3262
3263         priv->block_events_timeout_id = 0;
3264
3265         return FALSE;
3266 }
3267
3268 static void
3269 account_manager_prepared_cb (GObject *source_object,
3270                              GAsyncResult *result,
3271                              gpointer user_data)
3272 {
3273         GList *accounts, *l;
3274         TpAccountManager *account_manager = TP_ACCOUNT_MANAGER (source_object);
3275         EmpathyChat *chat = user_data;
3276         GError *error = NULL;
3277
3278         if (!tp_proxy_prepare_finish (account_manager, result, &error)) {
3279                 DEBUG ("Failed to prepare the account manager: %s", error->message);
3280                 g_error_free (error);
3281                 return;
3282         }
3283
3284         accounts = tp_account_manager_get_valid_accounts (account_manager);
3285
3286         for (l = accounts; l != NULL; l = l->next) {
3287                 TpAccount *account = l->data;
3288                 tp_g_signal_connect_object (account, "status-changed",
3289                                              G_CALLBACK (chat_new_connection_cb),
3290                                              chat, 0);
3291         }
3292
3293         g_list_free (accounts);
3294 }
3295
3296 static void
3297 empathy_chat_init (EmpathyChat *chat)
3298 {
3299         EmpathyChatPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chat,
3300                 EMPATHY_TYPE_CHAT, EmpathyChatPriv);
3301
3302         chat->priv = priv;
3303         priv->log_manager = tpl_log_manager_dup_singleton ();
3304         priv->gsettings_chat = g_settings_new (EMPATHY_PREFS_CHAT_SCHEMA);
3305         priv->gsettings_ui = g_settings_new (EMPATHY_PREFS_UI_SCHEMA);
3306
3307         priv->contacts_width = g_settings_get_int (priv->gsettings_ui,
3308                 EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS);
3309         priv->input_history = NULL;
3310         priv->input_history_current = NULL;
3311         priv->account_manager = tp_account_manager_dup ();
3312
3313         tp_proxy_prepare_async (priv->account_manager, NULL,
3314                                           account_manager_prepared_cb, chat);
3315
3316         priv->show_contacts = g_settings_get_boolean (priv->gsettings_chat,
3317                         EMPATHY_PREFS_CHAT_SHOW_CONTACTS_IN_ROOMS);
3318
3319         /* Block events for some time to avoid having "has come online" or
3320          * "joined" messages. */
3321         priv->block_events_timeout_id =
3322                 g_timeout_add_seconds (1, chat_block_events_timeout_cb, chat);
3323
3324         /* Add nick name completion */
3325         priv->completion = g_completion_new ((GCompletionFunc) empathy_contact_get_alias);
3326         g_completion_set_compare (priv->completion, chat_contacts_completion_func);
3327
3328         chat_create_ui (chat);
3329 }
3330
3331 EmpathyChat *
3332 empathy_chat_new (EmpathyTpChat *tp_chat)
3333 {
3334         return g_object_new (EMPATHY_TYPE_CHAT, "tp-chat", tp_chat, NULL);
3335 }
3336
3337 EmpathyTpChat *
3338 empathy_chat_get_tp_chat (EmpathyChat *chat)
3339 {
3340         EmpathyChatPriv *priv = GET_PRIV (chat);
3341
3342         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3343
3344         return priv->tp_chat;
3345 }
3346
3347 typedef struct
3348 {
3349         EmpathyChat *self;
3350         GtkWidget *info_bar;
3351         gulong response_id;
3352         GtkWidget *button;
3353         GtkWidget *label;
3354         GtkWidget *entry;
3355         GtkWidget *spinner;
3356         gchar *password;
3357 } PasswordData;
3358
3359 static void
3360 passwd_remember_button_cb (GtkButton *button,
3361                           PasswordData *data)
3362 {
3363         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3364 }
3365
3366 static void
3367 passwd_not_now_button_cb (GtkButton *button,
3368                           PasswordData *data)
3369 {
3370         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_NO);
3371 }
3372
3373 static void
3374 remember_password_infobar_response_cb (GtkWidget *info_bar,
3375                                        gint response_id,
3376                                        PasswordData *data)
3377 {
3378         EmpathyChatPriv *priv = GET_PRIV (data->self);
3379
3380         if (response_id == GTK_RESPONSE_OK) {
3381                 DEBUG ("Saving room password");
3382                 empathy_keyring_set_room_password_async (priv->account,
3383                                                          empathy_tp_chat_get_id (priv->tp_chat),
3384                                                          data->password,
3385                                                          NULL, NULL);
3386         }
3387
3388         gtk_widget_destroy (info_bar);
3389         g_free (data->password);
3390         g_slice_free (PasswordData, data);
3391 }
3392
3393 static void
3394 chat_prompt_to_save_password (EmpathyChat *self,
3395                               PasswordData *data)
3396 {
3397         GtkWidget *content_area;
3398         GtkWidget *hbox;
3399         GtkWidget *image;
3400         GtkWidget *label;
3401         GtkWidget *alig;
3402         GtkWidget *button;
3403
3404         /* save the password in case it needs to be saved */
3405         data->password = g_strdup (gtk_entry_get_text (GTK_ENTRY (data->entry)));
3406
3407         /* Remove all previous widgets */
3408         content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (data->info_bar));
3409         gtk_container_forall (GTK_CONTAINER (content_area),
3410                               (GtkCallback) gtk_widget_destroy, NULL);
3411         data->button = NULL;
3412         data->label = NULL;
3413         data->entry = NULL;
3414         data->spinner = NULL;
3415
3416         gtk_info_bar_set_message_type (GTK_INFO_BAR (data->info_bar),
3417                                        GTK_MESSAGE_QUESTION);
3418
3419         hbox = gtk_hbox_new (FALSE, 5);
3420         gtk_box_pack_start (GTK_BOX (content_area), hbox, TRUE, TRUE, 0);
3421
3422         /* Add image */
3423         image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_AUTHENTICATION,
3424                                           GTK_ICON_SIZE_DIALOG);
3425         gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
3426
3427         /* Add message */
3428         label = gtk_label_new (_("Would you like to store this password?"));
3429         gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0);
3430
3431         /* Add 'Remember' button */
3432         alig = gtk_alignment_new (0, 0.5, 1, 0);
3433
3434         button = gtk_button_new_with_label (_("Remember"));
3435         gtk_container_add (GTK_CONTAINER (alig), button);
3436         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3437
3438         g_signal_connect (button, "clicked", G_CALLBACK (passwd_remember_button_cb),
3439                           data);
3440
3441         /* Add 'Not now' button */
3442         alig = gtk_alignment_new (0, 0.5, 1, 0);
3443
3444         button = gtk_button_new_with_label (_("Not now"));
3445         gtk_container_add (GTK_CONTAINER (alig), button);
3446         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3447
3448         g_signal_connect (button, "clicked", G_CALLBACK (passwd_not_now_button_cb),
3449                           data);
3450
3451         /* go! */
3452         g_signal_handler_disconnect (data->info_bar, data->response_id);
3453         g_signal_connect (data->info_bar, "response",
3454                           G_CALLBACK (remember_password_infobar_response_cb), data);
3455
3456         gtk_widget_show_all (data->info_bar);
3457 }
3458
3459 static void
3460 provide_password_cb (GObject *tp_chat,
3461                      GAsyncResult *res,
3462                      gpointer user_data)
3463 {
3464         PasswordData *data = user_data;
3465         EmpathyChat *self = data->self;
3466         EmpathyChatPriv *priv = GET_PRIV (self);
3467         GError *error = NULL;
3468
3469         if (!tp_channel_provide_password_finish (TP_CHANNEL (tp_chat), res,
3470                                                       &error)) {
3471                 DEBUG ("error: %s", error->message);
3472                 /* FIXME: what should we do if that's another error? Close the channel?
3473                  * Display the raw D-Bus error to the user isn't very useful */
3474                 if (g_error_matches (error, TP_ERRORS, TP_ERROR_AUTHENTICATION_FAILED)) {
3475                         /* entry */
3476                         gtk_entry_set_text (GTK_ENTRY (data->entry), "");
3477                         gtk_widget_set_sensitive (data->entry, TRUE);
3478                         gtk_widget_grab_focus (data->entry);
3479
3480                         /* info bar */
3481                         gtk_info_bar_set_message_type (
3482                             GTK_INFO_BAR (data->info_bar),
3483                             GTK_MESSAGE_ERROR);
3484
3485                         /* button */
3486                         gtk_widget_set_sensitive (data->button, TRUE);
3487                         gtk_button_set_label (GTK_BUTTON (data->button),
3488                             _("Retry"));
3489
3490                         /* label */
3491                         gtk_label_set_text (GTK_LABEL (data->label),
3492                             _("Wrong password; please try again:"));
3493
3494                         /* spinner */
3495                         gtk_spinner_stop (GTK_SPINNER (data->spinner));
3496                         gtk_widget_hide (data->spinner);
3497                 }
3498                 g_error_free (error);
3499                 return;
3500         }
3501
3502         if (empathy_keyring_is_available ()) {
3503                 /* ask whether they want to save the password */
3504                 chat_prompt_to_save_password (self, data);
3505         } else {
3506                 /* Get rid of the password info bar finally */
3507                 gtk_widget_destroy (data->info_bar);
3508                 g_slice_free (PasswordData, data);
3509         }
3510
3511         /* Room joined */
3512         gtk_widget_set_sensitive (priv->hpaned, TRUE);
3513         gtk_widget_set_sensitive (self->input_text_view, TRUE);
3514         gtk_widget_grab_focus (self->input_text_view);
3515 }
3516
3517 static void
3518 password_infobar_response_cb (GtkWidget *info_bar,
3519                               gint response_id,
3520                               PasswordData *data)
3521 {
3522         EmpathyChatPriv *priv = GET_PRIV (data->self);
3523         const gchar *password;
3524
3525         if (response_id != GTK_RESPONSE_OK) {
3526                 gtk_widget_destroy (info_bar);
3527                 g_slice_free (PasswordData, data);
3528                 return;
3529         }
3530
3531         password = gtk_entry_get_text (GTK_ENTRY (data->entry));
3532
3533         tp_channel_provide_password_async (TP_CHANNEL (priv->tp_chat), password,
3534                                                 provide_password_cb, data);
3535
3536         gtk_widget_set_sensitive (data->button, FALSE);
3537         gtk_widget_set_sensitive (data->entry, FALSE);
3538
3539         gtk_spinner_start (GTK_SPINNER (data->spinner));
3540         gtk_widget_show (data->spinner);
3541 }
3542
3543 static void
3544 password_entry_activate_cb (GtkWidget *entry,
3545                           PasswordData *data)
3546 {
3547         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3548 }
3549
3550 static void
3551 passwd_join_button_cb (GtkButton *button,
3552                           PasswordData *data)
3553 {
3554         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3555 }
3556
3557 static void
3558 clear_icon_released_cb (GtkEntry *entry,
3559                         GtkEntryIconPosition icon_pos,
3560                         GdkEvent *event,
3561                         PasswordData *data)
3562 {
3563         gtk_entry_set_text (entry, "");
3564 }
3565
3566 static void
3567 password_entry_changed_cb (GtkEditable *entry,
3568                            PasswordData *data)
3569 {
3570         const gchar *str;
3571
3572         str = gtk_entry_get_text (GTK_ENTRY (entry));
3573
3574         gtk_entry_set_icon_sensitive (GTK_ENTRY (entry),
3575             GTK_ENTRY_ICON_SECONDARY, !EMP_STR_EMPTY (str));
3576 }
3577
3578 static void
3579 infobar_chat_invalidated_cb (TpProxy       *proxy,
3580                            guint          domain,
3581                            gint           code,
3582                            gchar         *message,
3583                            gpointer       password_infobar)
3584 {
3585         /* Destroy the password infobar whenever a channel is invalidated
3586          * so we don't have multiple infobars when the MUC is rejoined */
3587         gtk_widget_destroy (GTK_WIDGET (password_infobar));
3588 }
3589
3590 static void
3591 display_password_info_bar (EmpathyChat *self)
3592 {
3593         EmpathyChatPriv *priv = GET_PRIV (self);
3594         GtkWidget *info_bar;
3595         GtkWidget *content_area;
3596         GtkWidget *hbox;
3597         GtkWidget *image;
3598         GtkWidget *label;
3599         GtkWidget *entry;
3600         GtkWidget *alig;
3601         GtkWidget *button;
3602         GtkWidget *spinner;
3603         PasswordData *data;
3604
3605         data = g_slice_new0 (PasswordData);
3606
3607         info_bar = gtk_info_bar_new ();
3608         gtk_info_bar_set_message_type (GTK_INFO_BAR (info_bar),
3609             GTK_MESSAGE_QUESTION);
3610
3611         content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (info_bar));
3612
3613         hbox = gtk_hbox_new (FALSE, 5);
3614         gtk_box_pack_start (GTK_BOX (content_area), hbox, TRUE, TRUE, 0);
3615
3616         /* Add image */
3617         image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_AUTHENTICATION,
3618                                           GTK_ICON_SIZE_DIALOG);
3619         gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
3620
3621         /* Add message */
3622         label = gtk_label_new (_("This room is protected by a password:"));
3623         gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);
3624
3625         /* Add password entry */
3626         entry = gtk_entry_new ();
3627         gtk_entry_set_visibility (GTK_ENTRY (entry), FALSE);
3628         gtk_box_pack_start (GTK_BOX (hbox), entry, TRUE, TRUE, 0);
3629
3630         gtk_entry_set_icon_from_stock (GTK_ENTRY (entry),
3631                                        GTK_ENTRY_ICON_SECONDARY, GTK_STOCK_CLEAR);
3632         gtk_entry_set_icon_sensitive (GTK_ENTRY (entry),
3633                                       GTK_ENTRY_ICON_SECONDARY, FALSE);
3634
3635         g_signal_connect (entry, "icon-release",
3636                           G_CALLBACK (clear_icon_released_cb), data);
3637         g_signal_connect (entry, "changed",
3638                           G_CALLBACK (password_entry_changed_cb), data);
3639
3640         g_signal_connect (entry, "activate",
3641                           G_CALLBACK (password_entry_activate_cb), data);
3642
3643         /* Focus the password entry once it's realized */
3644         g_signal_connect (entry, "realize", G_CALLBACK (gtk_widget_grab_focus), NULL);
3645
3646         /* Add 'Join' button */
3647         alig = gtk_alignment_new (0, 0.5, 1, 0);
3648
3649         button = gtk_button_new_with_label (_("Join"));
3650         gtk_container_add (GTK_CONTAINER (alig), button);
3651         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3652
3653         g_signal_connect (button, "clicked", G_CALLBACK (passwd_join_button_cb),
3654                           data);
3655
3656         /* Add spinner */
3657         spinner = gtk_spinner_new ();
3658         gtk_box_pack_end (GTK_BOX (hbox), spinner, FALSE, FALSE, 0);
3659
3660         /* Save some data for messing around with later */
3661         data->self = self;
3662         data->info_bar = info_bar;
3663         data->button = button;
3664         data->label = label;
3665         data->entry = entry;
3666         data->spinner = spinner;
3667
3668         gtk_box_pack_start (GTK_BOX (priv->info_bar_vbox), info_bar,
3669                             TRUE, TRUE, 3);
3670         gtk_widget_show_all (hbox);
3671
3672         tp_g_signal_connect_object (priv->tp_chat,
3673                                   "invalidated", G_CALLBACK (infobar_chat_invalidated_cb),
3674                                   info_bar, 0);
3675
3676         data->response_id = g_signal_connect (info_bar, "response",
3677                                               G_CALLBACK (password_infobar_response_cb), data);
3678
3679         gtk_widget_show_all (info_bar);
3680         /* ... but hide the spinner */
3681         gtk_widget_hide (spinner);
3682
3683         /* prevent the user from typing anything */
3684         gtk_widget_set_sensitive (self->input_text_view, FALSE);
3685 }
3686
3687 static void
3688 provide_saved_password_cb (GObject *tp_chat,
3689                            GAsyncResult *res,
3690                            gpointer user_data)
3691 {
3692         EmpathyChat *self = user_data;
3693         EmpathyChatPriv *priv = GET_PRIV (self);
3694         GError *error = NULL;
3695
3696         if (!tp_channel_provide_password_finish (TP_CHANNEL (tp_chat), res,
3697                                                       &error)) {
3698                 DEBUG ("error: %s", error->message);
3699                 /* FIXME: what should we do if that's another error? Close the channel?
3700                  * Display the raw D-Bus error to the user isn't very useful */
3701                 if (g_error_matches (error, TP_ERRORS, TP_ERROR_AUTHENTICATION_FAILED)) {
3702                         display_password_info_bar (self);
3703                         gtk_widget_set_sensitive (priv->hpaned, FALSE);
3704                 }
3705                 g_error_free (error);
3706                 return;
3707         }
3708
3709         /* Room joined */
3710         gtk_widget_set_sensitive (priv->hpaned, TRUE);
3711         gtk_widget_grab_focus (self->input_text_view);
3712 }
3713
3714 static void
3715 chat_room_got_password_cb (GObject *source,
3716                            GAsyncResult *result,
3717                            gpointer user_data)
3718 {
3719         EmpathyChat *self = user_data;
3720         EmpathyChatPriv *priv = GET_PRIV (self);
3721         const gchar *password;
3722         GError *error = NULL;
3723
3724         password = empathy_keyring_get_room_password_finish (priv->account,
3725             result, &error);
3726
3727         if (error != NULL) {
3728                 DEBUG ("Couldn't get room password: %s\n", error->message);
3729                 g_clear_error (&error);
3730
3731                 display_password_info_bar (self);
3732                 gtk_widget_set_sensitive (priv->hpaned, FALSE);
3733                 return;
3734         }
3735
3736         tp_channel_provide_password_async (TP_CHANNEL (priv->tp_chat), password,
3737                                                 provide_saved_password_cb, self);
3738 }
3739
3740 static void
3741 chat_password_needed_changed_cb (EmpathyChat *self)
3742 {
3743         EmpathyChatPriv *priv = GET_PRIV (self);
3744
3745         if (tp_channel_password_needed (TP_CHANNEL (priv->tp_chat))) {
3746                 empathy_keyring_get_room_password_async (priv->account,
3747                                                          empathy_tp_chat_get_id (priv->tp_chat),
3748                                                          chat_room_got_password_cb, self);
3749         }
3750 }
3751
3752 static void
3753 chat_sms_channel_changed_cb (EmpathyChat *self)
3754 {
3755         EmpathyChatPriv *priv = GET_PRIV (self);
3756
3757         priv->sms_channel = tp_text_channel_is_sms_channel (
3758                 (TpTextChannel *) priv->tp_chat);
3759         g_object_notify (G_OBJECT (self), "sms-channel");
3760 }
3761
3762 static void
3763 chat_n_messages_sending_changed_cb (EmpathyChat *self)
3764 {
3765         g_object_notify (G_OBJECT (self), "n-messages-sending");
3766 }
3767
3768 void
3769 empathy_chat_set_tp_chat (EmpathyChat   *chat,
3770                           EmpathyTpChat *tp_chat)
3771 {
3772         EmpathyChatPriv *priv = GET_PRIV (chat);
3773         GPtrArray       *properties;
3774
3775         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3776         g_return_if_fail (EMPATHY_IS_TP_CHAT (tp_chat));
3777
3778         if (priv->tp_chat) {
3779                 return;
3780         }
3781
3782         if (priv->account) {
3783                 g_object_unref (priv->account);
3784         }
3785
3786         priv->tp_chat = g_object_ref (tp_chat);
3787         priv->account = g_object_ref (empathy_tp_chat_get_account (priv->tp_chat));
3788
3789         g_signal_connect (tp_chat, "invalidated",
3790                           G_CALLBACK (chat_invalidated_cb),
3791                           chat);
3792         g_signal_connect (tp_chat, "message-received-empathy",
3793                           G_CALLBACK (chat_message_received_cb),
3794                           chat);
3795         g_signal_connect (tp_chat, "message_acknowledged",
3796                           G_CALLBACK (chat_message_acknowledged_cb),
3797                           chat);
3798         g_signal_connect (tp_chat, "send-error",
3799                           G_CALLBACK (chat_send_error_cb),
3800                           chat);
3801         g_signal_connect (tp_chat, "chat-state-changed-empathy",
3802                           G_CALLBACK (chat_state_changed_cb),
3803                           chat);
3804         g_signal_connect (tp_chat, "property-changed",
3805                           G_CALLBACK (chat_property_changed_cb),
3806                           chat);
3807         g_signal_connect (tp_chat, "members-changed",
3808                           G_CALLBACK (chat_members_changed_cb),
3809                           chat);
3810         g_signal_connect (tp_chat, "member-renamed",
3811                           G_CALLBACK (chat_member_renamed_cb),
3812                           chat);
3813         g_signal_connect_swapped (tp_chat, "notify::remote-contact",
3814                                   G_CALLBACK (chat_remote_contact_changed_cb),
3815                                   chat);
3816         g_signal_connect_swapped (tp_chat, "notify::password-needed",
3817                                   G_CALLBACK (chat_password_needed_changed_cb),
3818                                   chat);
3819         g_signal_connect_swapped (tp_chat, "notify::is-sms-channel",
3820                                   G_CALLBACK (chat_sms_channel_changed_cb),
3821                                   chat);
3822         g_signal_connect_swapped (tp_chat, "notify::n-messages-sending",
3823                                   G_CALLBACK (chat_n_messages_sending_changed_cb),
3824                                   chat);
3825
3826         /* Get initial value of properties */
3827         properties = empathy_tp_chat_get_properties (priv->tp_chat);
3828         if (properties != NULL) {
3829                 guint i;
3830
3831                 for (i = 0; i < properties->len; i++) {
3832                         EmpathyTpChatProperty *property;
3833
3834                         property = g_ptr_array_index (properties, i);
3835                         if (property->value == NULL)
3836                                 continue;
3837
3838                         chat_property_changed_cb (priv->tp_chat,
3839                                                   property->name,
3840                                                   property->value,
3841                                                   chat);
3842                 }
3843         }
3844
3845         chat_sms_channel_changed_cb (chat);
3846         chat_remote_contact_changed_cb (chat);
3847
3848         if (chat->input_text_view) {
3849                 gtk_widget_set_sensitive (chat->input_text_view, TRUE);
3850                 if (priv->block_events_timeout_id == 0) {
3851                         empathy_chat_view_append_event (chat->view, _("Connected"));
3852                 }
3853         }
3854
3855         g_object_notify (G_OBJECT (chat), "tp-chat");
3856         g_object_notify (G_OBJECT (chat), "id");
3857         g_object_notify (G_OBJECT (chat), "account");
3858
3859         /* This is a noop when tp-chat is set at object construction time and causes
3860          * the pending messages to be show when it's set on the object after it has
3861          * been created */
3862         show_pending_messages (chat);
3863
3864         /* check if a password is needed */
3865         chat_password_needed_changed_cb (chat);
3866 }
3867
3868 TpAccount *
3869 empathy_chat_get_account (EmpathyChat *chat)
3870 {
3871         EmpathyChatPriv *priv = GET_PRIV (chat);
3872
3873         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3874
3875         return priv->account;
3876 }
3877
3878 const gchar *
3879 empathy_chat_get_id (EmpathyChat *chat)
3880 {
3881         EmpathyChatPriv *priv = GET_PRIV (chat);
3882
3883         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3884
3885         return priv->id;
3886 }
3887
3888 gchar *
3889 empathy_chat_dup_name (EmpathyChat *chat)
3890 {
3891         EmpathyChatPriv *priv = GET_PRIV (chat);
3892         const gchar *ret;
3893
3894         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3895
3896         ret = priv->name;
3897
3898         if (!ret && priv->remote_contact) {
3899                 ret = empathy_contact_get_alias (priv->remote_contact);
3900         }
3901
3902         if (!ret)
3903                 ret = priv->id;
3904
3905         if (!ret)
3906                 ret = _("Conversation");
3907
3908         if (priv->sms_channel)
3909                 /* Translators: this string is a something like
3910                  * "Escher Cat (SMS)" */
3911                 return g_strdup_printf (_("%s (SMS)"), ret);
3912         else
3913                 return g_strdup (ret);
3914 }
3915
3916 const gchar *
3917 empathy_chat_get_subject (EmpathyChat *chat)
3918 {
3919         EmpathyChatPriv *priv = GET_PRIV (chat);
3920
3921         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3922
3923         return priv->subject;
3924 }
3925
3926 EmpathyContact *
3927 empathy_chat_get_remote_contact (EmpathyChat *chat)
3928 {
3929         EmpathyChatPriv *priv = GET_PRIV (chat);
3930
3931         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3932
3933         return priv->remote_contact;
3934 }
3935
3936 GtkWidget *
3937 empathy_chat_get_contact_menu (EmpathyChat *chat)
3938 {
3939         EmpathyChatPriv *priv = GET_PRIV (chat);
3940         GtkWidget       *menu = NULL;
3941
3942         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3943
3944         if (priv->remote_contact) {
3945                 menu = empathy_contact_menu_new (priv->remote_contact,
3946                                                  EMPATHY_CONTACT_FEATURE_CALL |
3947                                                  EMPATHY_CONTACT_FEATURE_LOG |
3948                                                  EMPATHY_CONTACT_FEATURE_INFO |
3949                                                  EMPATHY_CONTACT_FEATURE_BLOCK);
3950         }
3951
3952         return menu;
3953 }
3954
3955 void
3956 empathy_chat_clear (EmpathyChat *chat)
3957 {
3958         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3959
3960         empathy_chat_view_clear (chat->view);
3961 }
3962
3963 void
3964 empathy_chat_scroll_down (EmpathyChat *chat)
3965 {
3966         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3967
3968         empathy_chat_view_scroll_down (chat->view);
3969 }
3970
3971 void
3972 empathy_chat_cut (EmpathyChat *chat)
3973 {
3974         GtkTextBuffer *buffer;
3975
3976         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3977
3978         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3979         if (gtk_text_buffer_get_has_selection (buffer)) {
3980                 GtkClipboard *clipboard;
3981
3982                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3983
3984                 gtk_text_buffer_cut_clipboard (buffer, clipboard, TRUE);
3985         }
3986 }
3987
3988 void
3989 empathy_chat_copy (EmpathyChat *chat)
3990 {
3991         GtkTextBuffer *buffer;
3992
3993         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3994
3995         if (empathy_chat_view_get_has_selection (chat->view)) {
3996                 empathy_chat_view_copy_clipboard (chat->view);
3997                 return;
3998         }
3999
4000         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
4001         if (gtk_text_buffer_get_has_selection (buffer)) {
4002                 GtkClipboard *clipboard;
4003
4004                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
4005
4006                 gtk_text_buffer_copy_clipboard (buffer, clipboard);
4007         }
4008         else {
4009                 gint start_offset;
4010                 gint end_offset;
4011                 EmpathyChatPriv *priv = GET_PRIV (chat);
4012
4013                 if (gtk_label_get_selection_bounds (GTK_LABEL (priv->label_topic),
4014                                                                &start_offset,
4015                                                                &end_offset)) {
4016                         gchar *start;
4017                         gchar *end;
4018                         gchar *selection;
4019                         const gchar *topic;
4020                         GtkClipboard *clipboard;
4021
4022                         topic = gtk_label_get_text (GTK_LABEL (priv->label_topic));
4023                         start = g_utf8_offset_to_pointer (topic, start_offset);
4024                         end = g_utf8_offset_to_pointer (topic, end_offset);
4025                         selection = g_strndup (start, end - start);
4026
4027                         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
4028                         gtk_clipboard_set_text (clipboard, selection, -1);
4029
4030                         g_free (selection);
4031                 }
4032         }
4033 }
4034
4035 void
4036 empathy_chat_paste (EmpathyChat *chat)
4037 {
4038         GtkTextBuffer *buffer;
4039         GtkClipboard  *clipboard;
4040         EmpathyChatPriv *priv;
4041
4042         g_return_if_fail (EMPATHY_IS_CHAT (chat));
4043
4044         priv = GET_PRIV (chat);
4045
4046         if (gtk_widget_get_visible (priv->search_bar)) {
4047                 empathy_search_bar_paste_clipboard (EMPATHY_SEARCH_BAR (priv->search_bar));
4048                 return;
4049         }
4050
4051         if (priv->tp_chat == NULL ||
4052             !gtk_widget_is_sensitive (chat->input_text_view))
4053                 return;
4054
4055         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
4056         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
4057
4058         gtk_text_buffer_paste_clipboard (buffer, clipboard, NULL, TRUE);
4059 }
4060
4061 void
4062 empathy_chat_find (EmpathyChat *chat)
4063 {
4064         EmpathyChatPriv *priv;
4065
4066         g_return_if_fail (EMPATHY_IS_CHAT (chat));
4067
4068         priv = GET_PRIV (chat);
4069
4070         empathy_search_bar_show (EMPATHY_SEARCH_BAR (priv->search_bar));
4071 }
4072
4073 void
4074 empathy_chat_correct_word (EmpathyChat  *chat,
4075                           GtkTextIter *start,
4076                           GtkTextIter *end,
4077                           const gchar *new_word)
4078 {
4079         GtkTextBuffer *buffer;
4080
4081         g_return_if_fail (chat != NULL);
4082         g_return_if_fail (new_word != NULL);
4083
4084         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
4085
4086         gtk_text_buffer_delete (buffer, start, end);
4087         gtk_text_buffer_insert (buffer, start,
4088                                 new_word,
4089                                 -1);
4090 }
4091
4092 gboolean
4093 empathy_chat_is_room (EmpathyChat *chat)
4094 {
4095         EmpathyChatPriv *priv = GET_PRIV (chat);
4096
4097         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
4098
4099         return (priv->handle_type == TP_HANDLE_TYPE_ROOM);
4100 }
4101
4102 guint
4103 empathy_chat_get_nb_unread_messages (EmpathyChat *self)
4104 {
4105         EmpathyChatPriv *priv = GET_PRIV (self);
4106
4107         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
4108
4109         return priv->unread_messages;
4110 }
4111
4112 /* called when the messages have been read by user */
4113 void
4114 empathy_chat_messages_read (EmpathyChat *self)
4115 {
4116         EmpathyChatPriv *priv = GET_PRIV (self);
4117
4118         g_return_if_fail (EMPATHY_IS_CHAT (self));
4119
4120         /* FIXME: See Bug#610994, See comments about it in EmpathyChatPriv
4121          * definition. If we are still retrieving the backlogs, do not ACK */
4122         if (priv->retrieving_backlogs)
4123                 return;
4124
4125         if (priv->tp_chat != NULL) {
4126                 tp_text_channel_ack_all_pending_messages_async (
4127                         TP_TEXT_CHANNEL (priv->tp_chat), NULL, NULL);
4128         }
4129
4130         if (priv->unread_messages_when_offline > 0) {
4131                 /* We can't ack those as the connection has gone away so just consider
4132                 * them as read. */
4133                 priv->unread_messages -= priv->unread_messages_when_offline;
4134                 g_object_notify (G_OBJECT (self), "nb-unread-messages");
4135                 priv->unread_messages_when_offline = 0;
4136         }
4137 }
4138
4139 /* Return TRUE if on of the contacts in this chat is composing */
4140 gboolean
4141 empathy_chat_is_composing (EmpathyChat *chat)
4142 {
4143   return chat->priv->compositors != NULL;
4144 }
4145
4146 gboolean
4147 empathy_chat_is_sms_channel (EmpathyChat *self)
4148 {
4149         EmpathyChatPriv *priv = GET_PRIV (self);
4150
4151         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
4152
4153         return priv->sms_channel;
4154 }
4155
4156 guint
4157 empathy_chat_get_n_messages_sending (EmpathyChat *self)
4158 {
4159         EmpathyChatPriv *priv;
4160
4161         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
4162
4163         priv = GET_PRIV (self);
4164
4165         if (priv->tp_chat == NULL) {
4166                 return 0;
4167         } else {
4168                 guint n_messages;
4169
4170                 g_object_get (priv->tp_chat,
4171                         "n-messages-sending", &n_messages,
4172                         NULL);
4173
4174                 return n_messages;
4175         }
4176 }
4177
4178 gchar *
4179 empathy_chat_dup_text (EmpathyChat *self)
4180 {
4181         GtkTextBuffer *buffer;
4182         GtkTextIter     start, end;
4183
4184         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (self->input_text_view));
4185
4186         gtk_text_buffer_get_bounds (buffer, &start, &end);
4187         return gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
4188 }
4189
4190 void
4191 empathy_chat_set_text (EmpathyChat *self,
4192                        const gchar *text)
4193 {
4194         GtkTextBuffer *buffer;
4195
4196         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (self->input_text_view));
4197
4198         gtk_text_buffer_set_text (buffer, text, -1);
4199 }