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