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