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