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