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