]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-chat.c
Replace tpl_text_event_dup_supersedes() with synthetic message
[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         /* TRUE if the pending messages can be displayed. This is to avoid to show
125          * pending messages *before* messages from logs. (#603980) */
126         gboolean           can_show_pending;
127
128         /* FIXME: retrieving_backlogs flag is a workaround for Bug#610994 and should
129          * be differently handled since it introduces another race condition, which
130          * is really hard to occur, but still possible.
131          *
132          * With the current workaround (which has the race above), we need to be
133          * sure to ACK any pending messages only when the retrieval of backlogs is
134          * finished, that's why using retrieving_backlogs flag.
135          * empathy_chat_messages_read () will check this variable and not ACK
136          * anything when TRUE. It will be set TRUE at chat_constructed () and set
137          * back to FALSE when the backlog has been retrieved and the pending
138          * messages actually showed to the user.
139          *
140          * Race condition introduced with this workaround:
141          * Scenario: a message is pending, the user is notified and selects the tab.
142          * the tab with a pending message is focused before the messages are properly
143          * shown (since the preparation of the window is slower AND async WRT the
144          * tab showing), which means the user won't see any new messages (rare but
145          * possible), if he/she will change tab focus before the messages are
146          * properly shown, the tab will be set as 'seen' and the user won't be
147          * notified again about the already notified pending messages when the
148          * messages in tab will be properly shown */
149         gboolean           retrieving_backlogs;
150         gboolean           sms_channel;
151 };
152
153 typedef struct {
154         gchar *text; /* Original message that was specified
155                       * upon entry creation. */
156         gchar *modified_text; /* Message that was modified by user.
157                                * When no modifications were made, it is NULL */
158 } InputHistoryEntry;
159
160 enum {
161         COMPOSING,
162         NEW_MESSAGE,
163         PART_COMMAND_ENTERED,
164         LAST_SIGNAL
165 };
166
167 enum {
168         PROP_0,
169         PROP_TP_CHAT,
170         PROP_ACCOUNT,
171         PROP_ID,
172         PROP_NAME,
173         PROP_SUBJECT,
174         PROP_REMOTE_CONTACT,
175         PROP_SHOW_CONTACTS,
176         PROP_SMS_CHANNEL,
177         PROP_N_MESSAGES_SENDING,
178         PROP_NB_UNREAD_MESSAGES,
179 };
180
181 static guint signals[LAST_SIGNAL] = { 0 };
182
183 G_DEFINE_TYPE (EmpathyChat, empathy_chat, GTK_TYPE_BIN);
184
185 static gboolean update_misspelled_words (gpointer data);
186
187 static void
188 chat_get_property (GObject    *object,
189                    guint       param_id,
190                    GValue     *value,
191                    GParamSpec *pspec)
192 {
193         EmpathyChat *chat = EMPATHY_CHAT (object);
194         EmpathyChatPriv *priv = GET_PRIV (object);
195
196         switch (param_id) {
197         case PROP_TP_CHAT:
198                 g_value_set_object (value, priv->tp_chat);
199                 break;
200         case PROP_ACCOUNT:
201                 g_value_set_object (value, priv->account);
202                 break;
203         case PROP_NAME:
204                 g_value_take_string (value, empathy_chat_dup_name (chat));
205                 break;
206         case PROP_ID:
207                 g_value_set_string (value, priv->id);
208                 break;
209         case PROP_SUBJECT:
210                 g_value_set_string (value, priv->subject);
211                 break;
212         case PROP_REMOTE_CONTACT:
213                 g_value_set_object (value, priv->remote_contact);
214                 break;
215         case PROP_SHOW_CONTACTS:
216                 g_value_set_boolean (value, priv->show_contacts);
217                 break;
218         case PROP_SMS_CHANNEL:
219                 g_value_set_boolean (value, priv->sms_channel);
220                 break;
221         case PROP_N_MESSAGES_SENDING:
222                 g_value_set_uint (value,
223                         empathy_chat_get_n_messages_sending (chat));
224                 break;
225         case PROP_NB_UNREAD_MESSAGES:
226                 g_value_set_uint (value,
227                         empathy_chat_get_nb_unread_messages (chat));
228                 break;
229         default:
230                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
231                 break;
232         };
233 }
234
235 static void
236 chat_set_property (GObject      *object,
237                    guint         param_id,
238                    const GValue *value,
239                    GParamSpec   *pspec)
240 {
241         EmpathyChat *chat = EMPATHY_CHAT (object);
242
243         switch (param_id) {
244         case PROP_TP_CHAT:
245                 empathy_chat_set_tp_chat (chat, EMPATHY_TP_CHAT (g_value_get_object (value)));
246                 break;
247         case PROP_SHOW_CONTACTS:
248                 empathy_chat_set_show_contacts (chat, g_value_get_boolean (value));
249                 break;
250         default:
251                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
252                 break;
253         };
254 }
255
256 static void
257 account_reconnected (EmpathyChat *chat,
258                         TpAccount *account)
259 {
260         EmpathyChatPriv *priv = GET_PRIV (chat);
261
262         DEBUG ("Account reconnected, request a new Text channel");
263
264         /* FIXME: Ideally we should ask to handle ourself the channel so we can
265         * report the error if any but this is blocked by
266         * https://bugs.freedesktop.org/show_bug.cgi?id=13422 */
267         switch (priv->handle_type) {
268                 case TP_HANDLE_TYPE_CONTACT:
269                         if (priv->sms_channel)
270                                 empathy_sms_contact_id (
271                                         account, priv->id,
272                                         TP_USER_ACTION_TIME_NOT_USER_ACTION);
273                         else
274                                 empathy_chat_with_contact_id (
275                                         account, priv->id,
276                                         TP_USER_ACTION_TIME_NOT_USER_ACTION);
277                         break;
278                 case TP_HANDLE_TYPE_ROOM:
279                         empathy_join_muc (account, priv->id,
280                                 TP_USER_ACTION_TIME_NOT_USER_ACTION);
281                         break;
282                 case TP_HANDLE_TYPE_NONE:
283                 case TP_HANDLE_TYPE_LIST:
284                 case TP_HANDLE_TYPE_GROUP:
285                 default:
286                         g_assert_not_reached ();
287                         break;
288         }
289
290         g_object_unref (chat);
291 }
292
293 static void
294 chat_new_connection_cb (TpAccount   *account,
295                         guint        old_status,
296                         guint        new_status,
297                         guint        reason,
298                         gchar       *dbus_error_name,
299                         GHashTable  *details,
300                         EmpathyChat *chat)
301 {
302         EmpathyChatPriv *priv = GET_PRIV (chat);
303
304         if (new_status != TP_CONNECTION_STATUS_CONNECTED)
305                 return;
306
307         if (priv->tp_chat != NULL || account != priv->account ||
308             priv->handle_type == TP_HANDLE_TYPE_NONE ||
309             EMP_STR_EMPTY (priv->id))
310                 return;
311
312         g_object_ref (chat);
313
314         account_reconnected (chat, account);
315 }
316
317 static void
318 chat_composing_remove_timeout (EmpathyChat *chat)
319 {
320         EmpathyChatPriv *priv;
321
322         priv = GET_PRIV (chat);
323
324         if (priv->composing_stop_timeout_id) {
325                 g_source_remove (priv->composing_stop_timeout_id);
326                 priv->composing_stop_timeout_id = 0;
327         }
328 }
329
330 static void
331 set_chate_state_cb (GObject *source,
332                     GAsyncResult *result,
333                     gpointer user_data)
334 {
335         GError *error = NULL;
336
337         if (!tp_text_channel_set_chat_state_finish (TP_TEXT_CHANNEL (source), result,
338                 &error)) {
339                 DEBUG ("Failed to set chat state: %s", error->message);
340                 g_error_free (error);
341         }
342 }
343
344 static void
345 set_chat_state (EmpathyChat *self,
346                 TpChannelChatState state)
347 {
348         EmpathyChatPriv *priv = GET_PRIV (self);
349
350         if (!tp_proxy_has_interface_by_id (priv->tp_chat,
351                 TP_IFACE_QUARK_CHANNEL_INTERFACE_CHAT_STATE))
352                 return;
353
354         tp_text_channel_set_chat_state_async (TP_TEXT_CHANNEL (priv->tp_chat), state,
355                 set_chate_state_cb, self);
356 }
357
358 static gboolean
359 chat_composing_stop_timeout_cb (EmpathyChat *chat)
360 {
361         EmpathyChatPriv *priv;
362
363         priv = GET_PRIV (chat);
364
365         priv->composing_stop_timeout_id = 0;
366         set_chat_state (chat, TP_CHANNEL_CHAT_STATE_PAUSED);
367
368         return FALSE;
369 }
370
371 static void
372 chat_composing_start (EmpathyChat *chat)
373 {
374         EmpathyChatPriv *priv;
375
376         priv = GET_PRIV (chat);
377
378         if (priv->composing_stop_timeout_id) {
379                 /* Just restart the timeout */
380                 chat_composing_remove_timeout (chat);
381         } else {
382                 set_chat_state (chat, TP_CHANNEL_CHAT_STATE_COMPOSING);
383         }
384
385         priv->composing_stop_timeout_id = g_timeout_add_seconds (
386                 COMPOSING_STOP_TIMEOUT,
387                 (GSourceFunc) chat_composing_stop_timeout_cb,
388                 chat);
389 }
390
391 static void
392 chat_composing_stop (EmpathyChat *chat)
393 {
394         chat_composing_remove_timeout (chat);
395         set_chat_state (chat, TP_CHANNEL_CHAT_STATE_ACTIVE);
396 }
397
398 static gint
399 chat_input_history_entry_cmp (InputHistoryEntry *entry,
400                               const gchar *text)
401 {
402         if (!tp_strdiff (entry->text, text)) {
403                 if (entry->modified_text != NULL) {
404                         /* Modified entry and single string cannot be equal. */
405                         return 1;
406                 }
407                 return 0;
408         }
409         return 1;
410 }
411
412 static InputHistoryEntry *
413 chat_input_history_entry_new_with_text (const gchar *text)
414 {
415         InputHistoryEntry *entry;
416         entry = g_slice_new0 (InputHistoryEntry);
417         entry->text = g_strdup (text);
418
419         return entry;
420 }
421
422 static void
423 chat_input_history_entry_free (InputHistoryEntry *entry)
424 {
425         g_free (entry->text);
426         g_free (entry->modified_text);
427         g_slice_free (InputHistoryEntry, entry);
428 }
429
430 static void
431 chat_input_history_entry_revert (InputHistoryEntry *entry)
432 {
433         g_free (entry->modified_text);
434         entry->modified_text = NULL;
435 }
436
437 static void
438 chat_input_history_entry_update_text (InputHistoryEntry *entry,
439                                       const gchar *text)
440 {
441         gchar *old;
442
443         if (!tp_strdiff (text, entry->text)) {
444                 g_free (entry->modified_text);
445                 entry->modified_text = NULL;
446                 return;
447         }
448
449         old = entry->modified_text;
450         entry->modified_text = g_strdup (text);
451         g_free (old);
452 }
453
454 static const gchar *
455 chat_input_history_entry_get_text (InputHistoryEntry *entry)
456 {
457         if (entry == NULL) {
458                 return NULL;
459         }
460
461         if (entry->modified_text != NULL) {
462                 return entry->modified_text;
463         }
464         return entry->text;
465 }
466
467 static GList *
468 chat_input_history_remove_item (GList *list,
469                                 GList *item)
470 {
471         list = g_list_remove_link (list, item);
472         chat_input_history_entry_free (item->data);
473         g_list_free_1 (item);
474         return list;
475 }
476
477 static void
478 chat_input_history_revert (EmpathyChat *chat)
479 {
480         EmpathyChatPriv   *priv;
481         GList             *list;
482         GList             *item1;
483         GList             *item2;
484         InputHistoryEntry *entry;
485
486         priv = GET_PRIV (chat);
487         list = priv->input_history;
488
489         if (list == NULL) {
490                 DEBUG ("No input history");
491                 return;
492         }
493
494         /* Delete temporary entry */
495         if (priv->input_history_current != NULL) {
496                 item1 = list;
497                 list = chat_input_history_remove_item (list, item1);
498                 if (priv->input_history_current == item1) {
499                         /* Removed temporary entry was current entry */
500                         priv->input_history = list;
501                         priv->input_history_current = NULL;
502                         return;
503                 }
504         }
505         else {
506                 /* There is no entry to revert */
507                 return;
508         }
509
510         /* Restore the current history entry to original value */
511         item1 = priv->input_history_current;
512         entry = item1->data;
513         chat_input_history_entry_revert (entry);
514
515         /* Remove restored entry if there is other occurance before this entry */
516         item2 = g_list_find_custom (list, chat_input_history_entry_get_text (entry),
517                                     (GCompareFunc) chat_input_history_entry_cmp);
518         if (item2 != item1) {
519                 list = chat_input_history_remove_item (list, item1);
520         }
521         else {
522                 /* Remove other occurance of the restored entry */
523                 item2 = g_list_find_custom (item1->next,
524                                             chat_input_history_entry_get_text (entry),
525                                             (GCompareFunc) chat_input_history_entry_cmp);
526                 if (item2 != NULL) {
527                         list = chat_input_history_remove_item (list, item2);
528                 }
529         }
530
531         priv->input_history_current = NULL;
532         priv->input_history = list;
533 }
534
535 static void
536 chat_input_history_add (EmpathyChat  *chat,
537                         const gchar *str,
538                         gboolean temporary)
539 {
540         EmpathyChatPriv   *priv;
541         GList             *list;
542         GList             *item;
543         InputHistoryEntry *entry;
544
545         priv = GET_PRIV (chat);
546
547         list = priv->input_history;
548
549         /* Remove any other occurances of this entry, if not temporary */
550         if (!temporary) {
551                 while ((item = g_list_find_custom (list, str,
552                     (GCompareFunc) chat_input_history_entry_cmp)) != NULL) {
553                         list = chat_input_history_remove_item (list, item);
554                 }
555
556                 /* Trim the list to the last 10 items */
557                 while (g_list_length (list) > 10) {
558                         item = g_list_last (list);
559                         if (item != NULL) {
560                                 list = chat_input_history_remove_item (list, item);
561                         }
562                 }
563         }
564
565
566
567         /* Add new entry */
568         entry = chat_input_history_entry_new_with_text (str);
569         list = g_list_prepend (list, entry);
570
571         /* Set the list and the current item pointer */
572         priv->input_history = list;
573         if (temporary) {
574                 priv->input_history_current = list;
575         }
576         else {
577                 priv->input_history_current = NULL;
578         }
579 }
580
581 static const gchar *
582 chat_input_history_get_next (EmpathyChat *chat)
583 {
584         EmpathyChatPriv *priv;
585         GList           *item;
586         const gchar     *msg;
587
588         priv = GET_PRIV (chat);
589
590         if (priv->input_history == NULL) {
591                 DEBUG ("No input history, next entry is NULL");
592                 return NULL;
593         }
594         g_assert (priv->input_history_current != NULL);
595
596         if ((item = g_list_next (priv->input_history_current)) == NULL)
597         {
598                 item = priv->input_history_current;
599         }
600
601         msg = chat_input_history_entry_get_text (item->data);
602
603         DEBUG ("Returning next entry: '%s'", msg);
604
605         priv->input_history_current = item;
606
607         return msg;
608 }
609
610 static const gchar *
611 chat_input_history_get_prev (EmpathyChat *chat)
612 {
613         EmpathyChatPriv *priv;
614         GList           *item;
615         const gchar     *msg;
616
617         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
618
619         priv = GET_PRIV (chat);
620
621         if (priv->input_history == NULL) {
622                 DEBUG ("No input history, previous entry is NULL");
623                 return NULL;
624         }
625
626         if (priv->input_history_current == NULL)
627         {
628                 return NULL;
629         }
630         else if ((item = g_list_previous (priv->input_history_current)) == NULL)
631         {
632                 item = priv->input_history_current;
633         }
634
635         msg = chat_input_history_entry_get_text (item->data);
636
637         DEBUG ("Returning previous entry: '%s'", msg);
638
639         priv->input_history_current = item;
640
641         return msg;
642 }
643
644 static void
645 chat_input_history_update (EmpathyChat *chat,
646                            GtkTextBuffer *buffer)
647 {
648         EmpathyChatPriv      *priv;
649         GtkTextIter           start, end;
650         gchar                *text;
651         InputHistoryEntry    *entry;
652
653         priv = GET_PRIV (chat);
654
655         gtk_text_buffer_get_bounds (buffer, &start, &end);
656         text = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
657
658         if (priv->input_history_current == NULL) {
659                 /* Add the current text temporarily to the history */
660                 chat_input_history_add (chat, text, TRUE);
661                 g_free (text);
662                 return;
663         }
664
665         /* Save the changes in the history */
666         entry = priv->input_history_current->data;
667         if (tp_strdiff (chat_input_history_entry_get_text (entry), text)) {
668                 chat_input_history_entry_update_text (entry, text);
669         }
670
671         g_free (text);
672 }
673
674 typedef struct {
675         EmpathyChat *chat;
676         gchar *message;
677 } ChatCommandMsgData;
678
679 static void
680 chat_command_msg_cb (GObject *source,
681                               GAsyncResult *result,
682                               gpointer                  user_data)
683 {
684         ChatCommandMsgData *data = user_data;
685         GError *error = NULL;
686         TpChannel *channel;
687
688         channel = tp_account_channel_request_ensure_and_observe_channel_finish (
689                                         TP_ACCOUNT_CHANNEL_REQUEST (source), result, &error);
690
691         if (channel == NULL) {
692                 DEBUG ("Failed to get channel: %s", error->message);
693                 g_error_free (error);
694
695                 empathy_chat_view_append_event (data->chat->view,
696                         _("Failed to open private chat"));
697                 goto OUT;
698         }
699
700         if (!EMP_STR_EMPTY (data->message) && TP_IS_TEXT_CHANNEL (channel)) {
701                 TpTextChannel *text = (TpTextChannel *) channel;
702                 TpMessage *msg;
703
704                 msg = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,
705                         data->message);
706
707                 tp_text_channel_send_message_async (text, msg, 0, NULL, NULL);
708
709                 g_object_unref (msg);
710         }
711
712         g_object_unref (channel);
713
714 OUT:
715         g_free (data->message);
716         g_slice_free (ChatCommandMsgData, data);
717 }
718
719 static gboolean
720 nick_command_supported (EmpathyChat *chat)
721 {
722         EmpathyChatPriv * priv = GET_PRIV (chat);
723         TpConnection    *connection;
724
725         connection = tp_channel_borrow_connection (TP_CHANNEL (priv->tp_chat));
726         return tp_proxy_has_interface_by_id (connection,
727                 EMP_IFACE_QUARK_CONNECTION_INTERFACE_RENAMING);
728 }
729
730 static gboolean
731 part_command_supported (EmpathyChat *chat)
732 {
733         EmpathyChatPriv * priv = GET_PRIV (chat);
734
735         return tp_proxy_has_interface_by_id (priv->tp_chat,
736                         TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP);
737 }
738
739 static void
740 chat_command_clear (EmpathyChat *chat,
741                     GStrv        strv)
742 {
743         empathy_chat_view_clear (chat->view);
744 }
745
746 static void
747 chat_command_topic (EmpathyChat *chat,
748                     GStrv        strv)
749 {
750         EmpathyChatPriv *priv = GET_PRIV (chat);
751         EmpathyTpChatProperty *property;
752         GValue value = {0, };
753
754         property = empathy_tp_chat_get_property (priv->tp_chat, "subject");
755         if (property == NULL) {
756                 empathy_chat_view_append_event (chat->view,
757                         _("Topic not supported on this conversation"));
758                 return;
759         }
760
761         if (!(property->flags & TP_PROPERTY_FLAG_WRITE)) {
762                 empathy_chat_view_append_event (chat->view,
763                         _("You are not allowed to change the topic"));
764                 return;
765         }
766
767         g_value_init (&value, G_TYPE_STRING);
768         g_value_set_string (&value, strv[1]);
769         empathy_tp_chat_set_property (priv->tp_chat, "subject", &value);
770         g_value_unset (&value);
771 }
772
773 void
774 empathy_chat_join_muc (EmpathyChat *chat,
775                    const gchar   *room)
776 {
777         EmpathyChatPriv *priv = GET_PRIV (chat);
778
779         empathy_join_muc (priv->account, room,
780                 empathy_get_current_action_time ());
781 }
782
783 static void
784 chat_command_join (EmpathyChat *chat,
785                    GStrv        strv)
786 {
787         guint i = 0;
788
789         GStrv rooms = g_strsplit_set (strv[1], ", ", -1);
790
791         /* FIXME: Ideally we should ask to handle ourself the channel so we can
792         * report the error if any but this is blocked by
793         * https://bugs.freedesktop.org/show_bug.cgi?id=13422 */
794         while (rooms[i] != NULL) {
795                 /* ignore empty strings */
796                 if (!EMP_STR_EMPTY (rooms[i])) {
797                         empathy_chat_join_muc (chat, rooms[i]);
798                 }
799                 i++;
800         }
801         g_strfreev (rooms);
802 }
803
804 static void
805 chat_command_part (EmpathyChat *chat,
806                            GStrv        strv)
807 {
808         g_signal_emit (chat, signals[PART_COMMAND_ENTERED], 0, strv);
809 }
810
811 static void
812 chat_command_msg_internal (EmpathyChat *chat,
813                            const gchar *contact_id,
814                            const gchar *message)
815 {
816         EmpathyChatPriv *priv = GET_PRIV (chat);
817         ChatCommandMsgData *data;
818         TpAccountChannelRequest *req;
819         GHashTable *request;
820
821         request = tp_asv_new (
822                 TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING, TP_IFACE_CHANNEL_TYPE_TEXT,
823                 TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT, TP_HANDLE_TYPE_CONTACT,
824                 TP_PROP_CHANNEL_TARGET_ID, G_TYPE_STRING, contact_id,
825                 NULL);
826
827         req = tp_account_channel_request_new (priv->account, request,
828                 empathy_get_current_action_time ());
829
830         /* FIXME: We should probably search in members alias. But this
831          * is enough for IRC */
832         data = g_slice_new (ChatCommandMsgData);
833         data->chat = chat;
834         data->message = g_strdup (message);
835
836         tp_account_channel_request_ensure_and_observe_channel_async (req,
837                 EMPATHY_CHAT_BUS_NAME, NULL, chat_command_msg_cb, data);
838
839         g_object_unref (req);
840         g_hash_table_unref (request);
841 }
842
843 static void
844 chat_command_query (EmpathyChat *chat,
845                     GStrv        strv)
846 {
847         /* If <message> part is not defined,
848          * strv[2] will be the terminal NULL */
849         chat_command_msg_internal (chat, strv[1], strv[2]);
850 }
851
852 static void
853 chat_command_msg (EmpathyChat *chat,
854                   GStrv        strv)
855 {
856         chat_command_msg_internal (chat, strv[1], strv[2]);
857 }
858
859 static void
860 callback_for_request_rename (TpProxy *proxy,
861                   const GError *error,
862                   gpointer user_data,
863                   GObject *weak_object)
864 {
865         if (error != NULL) {
866                 DEBUG ("Call to RequestRename method failed: %s",error->message);
867         }
868 }
869
870 static void
871 chat_command_nick (EmpathyChat *chat,
872                    GStrv        strv)
873 {
874         EmpathyChatPriv *priv = GET_PRIV (chat);
875         TpProxy *proxy;
876
877         proxy = TP_PROXY (tp_account_get_connection (priv->account));
878
879         emp_cli_connection_interface_renaming_call_request_rename (proxy, -1,
880                 strv[1], callback_for_request_rename, NULL, NULL, NULL);
881 }
882
883 static void
884 chat_command_me (EmpathyChat *chat,
885                   GStrv        strv)
886 {
887         EmpathyChatPriv *priv = GET_PRIV (chat);
888         TpMessage *message;
889         TpTextChannel *channel;
890
891         channel = (TpTextChannel *) (priv->tp_chat);
892
893         if (!tp_text_channel_supports_message_type (channel,
894                         TP_CHANNEL_TEXT_MESSAGE_TYPE_ACTION)) {
895                 /* Action message are not supported, 'simulate' the action */
896                 EmpathyContact *self_contact;
897                 gchar *tmp;
898
899                 self_contact = empathy_tp_chat_get_self_contact (priv->tp_chat);
900                 /* The TpChat can't be ready if it doesn't have the self contact */
901                 g_assert (self_contact != NULL);
902
903                 tmp = g_strdup_printf ("%s %s", empathy_contact_get_alias (self_contact),
904                         strv[1]);
905                 message = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,
906                         tmp);
907                 g_free (tmp);
908         }
909         else {
910                 message = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_ACTION,
911                         strv[1]);
912         }
913
914         empathy_tp_chat_send (priv->tp_chat, message);
915         g_object_unref (message);
916 }
917
918 static void
919 chat_command_say (EmpathyChat *chat,
920                   GStrv        strv)
921 {
922         EmpathyChatPriv *priv = GET_PRIV (chat);
923         TpMessage *message;
924
925         message = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,
926                 strv[1]);
927         empathy_tp_chat_send (priv->tp_chat, message);
928         g_object_unref (message);
929 }
930
931 static void
932 whois_got_contact_cb (TpConnection *connection,
933                       guint n_contacts,
934                       TpContact * const *contacts,
935                       const gchar * const *requested_ids,
936                       GHashTable *failed_id_errors,
937                       const GError *error,
938                       gpointer user_data,
939                       GObject *weak_object)
940 {
941         EmpathyChat *chat = EMPATHY_CHAT (weak_object);
942
943         g_return_if_fail (n_contacts <= 1);
944
945         if (n_contacts == 0) {
946                 GHashTableIter iter;
947                 gpointer key = NULL, value = NULL;
948                 gchar *id;
949                 GError *id_error;
950
951                 /* tp-glib guarantees that the contacts you requested will be
952                  * in failed_id_errors regardless of whether the individual
953                  * contact was invalid or the whole operation failed.
954                  */
955                 g_hash_table_iter_init (&iter, failed_id_errors);
956                 g_hash_table_iter_next (&iter, &key, &value);
957                 id = key;
958                 id_error = value;
959
960                 DEBUG ("Error getting TpContact for '%s': %s %u %s",
961                         id, g_quark_to_string (id_error->domain),
962                         id_error->code, id_error->message);
963
964                 if (error == NULL) {
965                         /* The specific ID failed. */
966                         gchar *event = g_strdup_printf (
967                                 _("“%s” is not a valid contact ID"), id);
968                         empathy_chat_view_append_event (chat->view, event);
969                         g_free (event);
970                 }
971                 /* Otherwise we're disconnected or something; so the window
972                  * will already say ‘Disconnected’, so let's not show anything.
973                  */
974         } else {
975                 EmpathyContact *empathy_contact;
976                 GtkWidget *window;
977
978                 g_return_if_fail (contacts[0] != NULL);
979                 empathy_contact = empathy_contact_dup_from_tp_contact (
980                         contacts[0]);
981
982                 window = gtk_widget_get_toplevel (GTK_WIDGET (chat));
983                 /* If we're alive and this command is running, we'd better be
984                  * in a window. */
985                 g_return_if_fail (window != NULL);
986                 g_return_if_fail (gtk_widget_is_toplevel (window));
987                 empathy_contact_information_dialog_show (empathy_contact,
988                         GTK_WINDOW (window));
989                 g_object_unref (empathy_contact);
990         }
991 }
992
993 static void
994 chat_command_whois (EmpathyChat *chat,
995                     GStrv strv)
996 {
997         EmpathyChatPriv *priv = GET_PRIV (chat);
998         TpConnection *conn;
999
1000         conn = tp_channel_borrow_connection ((TpChannel *) priv->tp_chat);
1001         tp_connection_get_contacts_by_id (conn,
1002                 /* Element 0 of 'strv' is "whois"; element 1 is the contact ID
1003                  * entered by the user (including spaces, if any). */
1004                 1, (const gchar * const *) strv + 1,
1005                 0, NULL,
1006                 whois_got_contact_cb, NULL, NULL, G_OBJECT (chat));
1007 }
1008
1009 static void chat_command_help (EmpathyChat *chat, GStrv strv);
1010
1011 typedef void (*ChatCommandFunc) (EmpathyChat *chat, GStrv strv);
1012
1013 typedef struct {
1014         const gchar *prefix;
1015         guint min_parts;
1016         guint max_parts;
1017         ChatCommandFunc func;
1018         gboolean (*is_supported)(EmpathyChat *chat);
1019         const gchar *help;
1020 } ChatCommandItem;
1021
1022 static ChatCommandItem commands[] = {
1023         {"clear", 1, 1, chat_command_clear, NULL,
1024          N_("/clear: clear all messages from the current conversation")},
1025
1026         {"topic", 2, 2, chat_command_topic, NULL,
1027          N_("/topic <topic>: set the topic of the current conversation")},
1028
1029         {"join", 2, 2, chat_command_join, NULL,
1030          N_("/join <chat room ID>: join a new chat room")},
1031
1032         {"j", 2, 2, chat_command_join, NULL,
1033          N_("/j <chat room ID>: join a new chat room")},
1034
1035         /* FIXME: https://bugzilla.gnome.org/show_bug.cgi?id=643295 */
1036         {"part", 1, 3, chat_command_part, part_command_supported,
1037          N_("/part [<chat room ID>] [<reason>]: leave the chat room, "
1038             "by default the current one")},
1039
1040         {"query", 2, 3, chat_command_query, NULL,
1041          N_("/query <contact ID> [<message>]: open a private chat")},
1042
1043         {"msg", 3, 3, chat_command_msg, NULL,
1044          N_("/msg <contact ID> <message>: open a private chat")},
1045
1046         {"nick", 2, 2, chat_command_nick, nick_command_supported,
1047          N_("/nick <nickname>: change your nickname on the current server")},
1048
1049         {"me", 2, 2, chat_command_me, NULL,
1050          N_("/me <message>: send an ACTION message to the current conversation")},
1051
1052         {"say", 2, 2, chat_command_say, NULL,
1053          N_("/say <message>: send <message> to the current conversation. "
1054             "This is used to send a message starting with a '/'. For example: "
1055             "\"/say /join is used to join a new chat room\"")},
1056
1057         {"whois", 2, 2, chat_command_whois, NULL,
1058          N_("/whois <contact ID>: display information about a contact")},
1059
1060         {"help", 1, 2, chat_command_help, NULL,
1061          N_("/help [<command>]: show all supported commands. "
1062             "If <command> is defined, show its usage.")},
1063 };
1064
1065 static void
1066 chat_command_show_help (EmpathyChat     *chat,
1067                         ChatCommandItem *item)
1068 {
1069         gchar *str;
1070
1071         str = g_strdup_printf (_("Usage: %s"), _(item->help));
1072         empathy_chat_view_append_event (chat->view, str);
1073         g_free (str);
1074 }
1075
1076 static void
1077 chat_command_help (EmpathyChat *chat,
1078                    GStrv        strv)
1079 {
1080         guint i;
1081
1082         /* If <command> part is not defined,
1083          * strv[1] will be the terminal NULL */
1084         if (strv[1] == NULL) {
1085                 for (i = 0; i < G_N_ELEMENTS (commands); i++) {
1086                         if (commands[i].is_supported != NULL) {
1087                                 if (!commands[i].is_supported (chat)) {
1088                                         continue;
1089                                 }
1090                         }
1091                     empathy_chat_view_append_event (chat->view,
1092                             _(commands[i].help));
1093                 }
1094                 return;
1095         }
1096
1097         for (i = 0; i < G_N_ELEMENTS (commands); i++) {
1098                 if (g_ascii_strcasecmp (strv[1], commands[i].prefix) == 0) {
1099                         if (commands[i].is_supported != NULL) {
1100                                 if (!commands[i].is_supported (chat)) {
1101                                         break;
1102                                 }
1103                         }
1104                         chat_command_show_help (chat, &commands[i]);
1105                         return;
1106                 }
1107         }
1108
1109         empathy_chat_view_append_event (chat->view,
1110                 _("Unknown command"));
1111 }
1112
1113 static GStrv
1114 chat_command_parse (const gchar *text, guint max_parts)
1115 {
1116         GPtrArray *array;
1117         gchar *item;
1118
1119         DEBUG ("Parse command, parts=%d text=\"%s\":", max_parts, text);
1120
1121         array = g_ptr_array_sized_new (max_parts + 1);
1122         while (max_parts > 1) {
1123                 const gchar *end;
1124
1125                 /* Skip white spaces */
1126                 while (g_ascii_isspace (*text)) {
1127                         text++;
1128                 }
1129
1130                 /* Search the end of this part, until first space. */
1131                 for (end = text; *end != '\0' && !g_ascii_isspace (*end); end++)
1132                         /* Do nothing */;
1133                 if (*end == '\0') {
1134                         break;
1135                 }
1136
1137                 item = g_strndup (text, end - text);
1138                 g_ptr_array_add (array, item);
1139                 DEBUG ("\tITEM: \"%s\"", item);
1140
1141                 text = end;
1142                 max_parts--;
1143         }
1144
1145         /* Append last part if not empty */
1146         item = g_strstrip (g_strdup (text));
1147         if (!EMP_STR_EMPTY (item)) {
1148                 g_ptr_array_add (array, item);
1149                 DEBUG ("\tITEM: \"%s\"", item);
1150         } else {
1151                 g_free (item);
1152         }
1153
1154         /* Make the array NULL-terminated */
1155         g_ptr_array_add (array, NULL);
1156
1157         return (GStrv) g_ptr_array_free (array, FALSE);
1158 }
1159
1160 static gboolean
1161 has_prefix_case (const gchar *s,
1162                   const gchar *prefix)
1163 {
1164         return g_ascii_strncasecmp (s, prefix, strlen (prefix)) == 0;
1165 }
1166
1167 static void
1168 chat_send (EmpathyChat  *chat,
1169            const gchar *msg)
1170 {
1171         EmpathyChatPriv *priv;
1172         TpMessage  *message;
1173         guint            i;
1174
1175         if (EMP_STR_EMPTY (msg)) {
1176                 return;
1177         }
1178
1179         priv = GET_PRIV (chat);
1180
1181         chat_input_history_add (chat, msg, FALSE);
1182
1183         if (msg[0] == '/') {
1184                 gboolean second_slash = FALSE;
1185                 const gchar *iter = msg + 1;
1186
1187                 for (i = 0; i < G_N_ELEMENTS (commands); i++) {
1188                         GStrv strv;
1189                         guint strv_len;
1190                         gchar c;
1191
1192                         if (!has_prefix_case (msg + 1, commands[i].prefix)) {
1193                                 continue;
1194                         }
1195                         c = *(msg + 1 + strlen (commands[i].prefix));
1196                         if (c != '\0' && !g_ascii_isspace (c)) {
1197                                 continue;
1198                         }
1199                         if (commands[i].is_supported != NULL) {
1200                                 if (!commands[i].is_supported (chat)) {
1201                                         continue;
1202                                 }
1203                         }
1204
1205                         /* We can't use g_strsplit here because it does
1206                          * not deal correctly if we have more than one space
1207                          * between args */
1208                         strv = chat_command_parse (msg + 1, commands[i].max_parts);
1209
1210                         strv_len = g_strv_length (strv);
1211                         if (strv_len < commands[i].min_parts ||
1212                             strv_len > commands[i].max_parts) {
1213                                 chat_command_show_help (chat, &commands[i]);
1214                                 g_strfreev (strv);
1215                                 return;
1216                         }
1217
1218                         commands[i].func (chat, strv);
1219                         g_strfreev (strv);
1220                         return;
1221                 }
1222
1223                 /* Also allow messages with two slashes before the
1224                  * first space, so it is possible to send a /unix/path.
1225                  * This heuristic is kind of crap. */
1226                 while (*iter != '\0' && !g_ascii_isspace (*iter)) {
1227                         if (*iter == '/') {
1228                                 second_slash = TRUE;
1229                                 break;
1230                         }
1231                         iter++;
1232                 }
1233
1234                 if (!second_slash) {
1235                         empathy_chat_view_append_event (chat->view,
1236                                 _("Unknown command; see /help for the available"
1237                                   " commands"));
1238                         return;
1239                 }
1240         }
1241
1242         message = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,
1243                 msg);
1244         empathy_tp_chat_send (priv->tp_chat, message);
1245         g_object_unref (message);
1246 }
1247
1248 static void
1249 chat_input_text_view_send (EmpathyChat *chat)
1250 {
1251         GtkTextBuffer  *buffer;
1252         GtkTextIter     start, end;
1253         gchar          *msg;
1254
1255         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1256
1257         gtk_text_buffer_get_bounds (buffer, &start, &end);
1258         msg = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1259
1260         /* clear the input field */
1261         gtk_text_buffer_set_text (buffer, "", -1);
1262         /* delete input history modifications */
1263         chat_input_history_revert (chat);
1264
1265         chat_send (chat, msg);
1266         g_free (msg);
1267 }
1268
1269 static void
1270 chat_state_changed_cb (EmpathyTpChat      *tp_chat,
1271                        EmpathyContact     *contact,
1272                        TpChannelChatState  state,
1273                        EmpathyChat        *chat)
1274 {
1275         EmpathyChatPriv *priv;
1276         GList          *l;
1277         gboolean        was_composing;
1278
1279         priv = GET_PRIV (chat);
1280
1281         if (empathy_contact_is_user (contact)) {
1282                 /* We don't care about our own chat state */
1283                 return;
1284         }
1285
1286         was_composing = (priv->compositors != NULL);
1287
1288         /* Find the contact in the list. After that l is the list elem or NULL */
1289         for (l = priv->compositors; l; l = l->next) {
1290                 if (contact == l->data) {
1291                         break;
1292                 }
1293         }
1294
1295         switch (state) {
1296         case TP_CHANNEL_CHAT_STATE_GONE:
1297         case TP_CHANNEL_CHAT_STATE_INACTIVE:
1298         case TP_CHANNEL_CHAT_STATE_PAUSED:
1299         case TP_CHANNEL_CHAT_STATE_ACTIVE:
1300                 /* Contact is not composing */
1301                 if (l) {
1302                         priv->compositors = g_list_remove_link (priv->compositors, l);
1303                         g_object_unref (l->data);
1304                         g_list_free1 (l);
1305                 }
1306                 break;
1307         case TP_CHANNEL_CHAT_STATE_COMPOSING:
1308                 /* Contact is composing */
1309                 if (!l) {
1310                         priv->compositors = g_list_prepend (priv->compositors,
1311                                                             g_object_ref (contact));
1312                 }
1313                 break;
1314         default:
1315                 g_assert_not_reached ();
1316         }
1317
1318         DEBUG ("Was composing: %s now composing: %s",
1319                 was_composing ? "yes" : "no",
1320                 priv->compositors ? "yes" : "no");
1321
1322         if ((was_composing && !priv->compositors) ||
1323             (!was_composing && priv->compositors)) {
1324                 /* Composing state changed */
1325                 g_signal_emit (chat, signals[COMPOSING], 0,
1326                                priv->compositors != NULL);
1327         }
1328 }
1329
1330 static void
1331 chat_message_received (EmpathyChat *chat,
1332         EmpathyMessage *message,
1333         gboolean pending)
1334 {
1335         EmpathyChatPriv *priv = GET_PRIV (chat);
1336
1337         if (empathy_message_is_edit (message)) {
1338                 DEBUG ("Editing message '%s' to '%s'",
1339                         empathy_message_get_supersedes (message),
1340                         empathy_message_get_body (message));
1341
1342                 empathy_chat_view_edit_message (chat->view, message);
1343
1344                 /* FIXME: do we need to do things like edit the chat state? */
1345         } else {
1346                 EmpathyContact  *sender;
1347
1348                 sender = empathy_message_get_sender (message);
1349
1350                 DEBUG ("Appending new message '%s' from %s (%d)",
1351                         empathy_message_get_token (message),
1352                         empathy_contact_get_alias (sender),
1353                         empathy_contact_get_handle (sender));
1354
1355                 empathy_chat_view_append_message (chat->view, message);
1356
1357                 /* We received a message so the contact is no longer
1358                  * composing */
1359                 chat_state_changed_cb (priv->tp_chat, sender,
1360                                        TP_CHANNEL_CHAT_STATE_ACTIVE,
1361                                        chat);
1362
1363                 if (empathy_message_is_incoming (message)) {
1364                         priv->unread_messages++;
1365                         g_object_notify (G_OBJECT (chat), "nb-unread-messages");
1366                 }
1367
1368                 g_signal_emit (chat, signals[NEW_MESSAGE], 0, message, pending);
1369         }
1370 }
1371
1372 static void
1373 chat_message_received_cb (EmpathyTpChat  *tp_chat,
1374                           EmpathyMessage *message,
1375                           EmpathyChat    *chat)
1376 {
1377         chat_message_received (chat, message, FALSE);
1378 }
1379
1380 static void
1381 chat_message_acknowledged_cb (EmpathyTpChat  *tp_chat,
1382                               EmpathyMessage *message,
1383                               EmpathyChat    *chat)
1384 {
1385         EmpathyChatPriv *priv = GET_PRIV (chat);
1386
1387         empathy_chat_view_message_acknowledged (chat->view,
1388             message);
1389
1390         priv->unread_messages--;
1391         g_object_notify (G_OBJECT (chat), "nb-unread-messages");
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
2694 static gboolean
2695 update_misspelled_words (gpointer data)
2696 {
2697         EmpathyChat *chat = EMPATHY_CHAT (data);
2698         EmpathyChatPriv *priv = GET_PRIV (chat);
2699         GtkTextBuffer *buffer;
2700         GtkTextIter iter;
2701         gint length;
2702
2703         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2704
2705         gtk_text_buffer_get_end_iter (buffer, &iter);
2706         length = gtk_text_iter_get_offset (&iter);
2707         chat_input_text_buffer_insert_text_cb (buffer, &iter,
2708                                                NULL, length, chat);
2709
2710         priv->update_misspelled_words_id = 0;
2711
2712         return FALSE;
2713 }
2714
2715 static void
2716 conf_spell_checking_cb (GSettings *gsettings_chat,
2717                         const gchar *key,
2718                         gpointer user_data)
2719 {
2720         EmpathyChat *chat = EMPATHY_CHAT (user_data);
2721         EmpathyChatPriv *priv = GET_PRIV (chat);
2722         gboolean spell_checker;
2723         GtkTextBuffer *buffer;
2724
2725         if (strcmp (key, EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED) != 0)
2726                 return;
2727
2728         spell_checker = g_settings_get_boolean (gsettings_chat,
2729                         EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED);
2730
2731         if (!empathy_spell_supported ()) {
2732                 spell_checker = FALSE;
2733         }
2734
2735         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2736
2737         if (spell_checker == priv->spell_checking_enabled) {
2738                 if (spell_checker) {
2739                         /* Possibly changed dictionaries,
2740                          * update misspelled words. Need to do so in idle
2741                          * so the spell checker is updated. */
2742                         priv->update_misspelled_words_id =
2743                                 g_idle_add (update_misspelled_words, chat);
2744                 }
2745
2746                 return;
2747         }
2748
2749         if (spell_checker) {
2750                 GtkTextIter iter;
2751
2752                 priv->notify_cursor_position_id = tp_g_signal_connect_object  (
2753                                 buffer, "notify::cursor-position",
2754                                 G_CALLBACK (chat_input_text_buffer_notify_cursor_position_cb),
2755                                 chat, 0);
2756                 priv->insert_text_id = tp_g_signal_connect_object  (
2757                                 buffer, "insert-text",
2758                                 G_CALLBACK (chat_input_text_buffer_insert_text_cb),
2759                                 chat, G_CONNECT_AFTER);
2760                 priv->delete_range_id = tp_g_signal_connect_object  (
2761                                 buffer, "delete-range",
2762                                 G_CALLBACK (chat_input_text_buffer_delete_range_cb),
2763                                 chat, G_CONNECT_AFTER);
2764
2765                 gtk_text_buffer_create_tag (buffer, "misspelled",
2766                                             "underline", PANGO_UNDERLINE_ERROR,
2767                                             NULL);
2768
2769                 gtk_text_buffer_get_iter_at_mark (buffer, &iter,
2770                                                   gtk_text_buffer_get_insert (buffer));
2771                 gtk_text_buffer_create_mark (buffer, "previous-cursor-position",
2772                                              &iter, TRUE);
2773
2774                 /* Mark misspelled words in the existing buffer.
2775                  * Need to do so in idle so the spell checker is updated. */
2776                 priv->update_misspelled_words_id =
2777                         g_idle_add (update_misspelled_words, chat);
2778         } else {
2779                 GtkTextTagTable *table;
2780                 GtkTextTag *tag;
2781
2782                 g_signal_handler_disconnect (buffer, priv->notify_cursor_position_id);
2783                 priv->notify_cursor_position_id = 0;
2784                 g_signal_handler_disconnect (buffer, priv->insert_text_id);
2785                 priv->insert_text_id = 0;
2786                 g_signal_handler_disconnect (buffer, priv->delete_range_id);
2787                 priv->delete_range_id = 0;
2788
2789                 table = gtk_text_buffer_get_tag_table (buffer);
2790                 tag = gtk_text_tag_table_lookup (table, "misspelled");
2791                 gtk_text_tag_table_remove (table, tag);
2792
2793                 gtk_text_buffer_delete_mark_by_name (buffer,
2794                                                      "previous-cursor-position");
2795         }
2796
2797         priv->spell_checking_enabled = spell_checker;
2798 }
2799
2800 static gboolean
2801 save_paned_pos_timeout (gpointer data)
2802 {
2803         EmpathyChat *self = data;
2804         gint hpaned_pos;
2805
2806         hpaned_pos = gtk_paned_get_position (GTK_PANED (self->priv->hpaned));
2807
2808         g_settings_set_int (self->priv->gsettings_ui,
2809                             EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS,
2810                             hpaned_pos);
2811
2812         return FALSE;
2813 }
2814
2815 static gboolean
2816 chat_hpaned_pos_changed_cb (GtkWidget* hpaned,
2817                 GParamSpec *spec,
2818                 gpointer user_data)
2819 {
2820         EmpathyChat *chat = EMPATHY_CHAT (user_data);
2821
2822         if (chat->priv->save_paned_pos_id != 0)
2823                 g_source_remove (chat->priv->save_paned_pos_id);
2824
2825         chat->priv->save_paned_pos_id = g_timeout_add_seconds (1,
2826                 save_paned_pos_timeout, chat);
2827
2828         return TRUE;
2829 }
2830
2831 static void
2832 chat_create_ui (EmpathyChat *chat)
2833 {
2834         EmpathyChatPriv *priv = GET_PRIV (chat);
2835         GtkBuilder      *gui;
2836         GList           *list = NULL;
2837         gchar           *filename;
2838         GtkTextBuffer   *buffer;
2839         gint              paned_pos;
2840         EmpathyThemeManager *theme_mgr;
2841
2842         filename = empathy_file_lookup ("empathy-chat.ui",
2843                                         "libempathy-gtk");
2844         gui = empathy_builder_get_file (filename,
2845                                         "chat_widget", &priv->widget,
2846                                         "hpaned", &priv->hpaned,
2847                                         "vbox_left", &priv->vbox_left,
2848                                         "scrolled_window_chat", &priv->scrolled_window_chat,
2849                                         "scrolled_window_input", &priv->scrolled_window_input,
2850                                         "hbox_topic", &priv->hbox_topic,
2851                                         "expander_topic", &priv->expander_topic,
2852                                         "label_topic", &priv->label_topic,
2853                                         "scrolled_window_contacts", &priv->scrolled_window_contacts,
2854                                         "info_bar_vbox", &priv->info_bar_vbox,
2855                                         NULL);
2856
2857         empathy_builder_connect (gui, chat,
2858                 "expander_topic", "notify::expanded", chat_topic_expander_activate_cb,
2859                 "label_topic", "size-allocate", chat_topic_label_size_allocate_cb,
2860                 NULL);
2861
2862         g_free (filename);
2863
2864         /* Add message view. */
2865         theme_mgr = empathy_theme_manager_dup_singleton ();
2866         chat->view = empathy_theme_manager_create_view (theme_mgr);
2867         g_object_unref (theme_mgr);
2868         /* If this is a GtkTextView, it's set as a drag destination for text/plain
2869            and other types, even though it's non-editable and doesn't accept any
2870            drags.  This steals drag motion for anything inside the scrollbars,
2871            making drag destinations on chat windows far less useful.
2872          */
2873         gtk_drag_dest_unset (GTK_WIDGET (chat->view));
2874         g_signal_connect (chat->view, "focus_in_event",
2875                           G_CALLBACK (chat_text_view_focus_in_event_cb),
2876                           chat);
2877         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_chat),
2878                            GTK_WIDGET (chat->view));
2879         gtk_widget_show (GTK_WIDGET (chat->view));
2880
2881         /* Add input GtkTextView */
2882         chat->input_text_view = empathy_input_text_view_new ();
2883         g_signal_connect (chat->input_text_view, "notify::has-focus",
2884                           G_CALLBACK (chat_input_has_focus_notify_cb),
2885                           chat);
2886         g_signal_connect (chat->input_text_view, "key-press-event",
2887                           G_CALLBACK (chat_input_key_press_event_cb),
2888                           chat);
2889         g_signal_connect (chat->input_text_view, "realize",
2890                           G_CALLBACK (chat_input_realize_cb),
2891                           chat);
2892         g_signal_connect (chat->input_text_view, "populate-popup",
2893                           G_CALLBACK (chat_input_populate_popup_cb),
2894                           chat);
2895         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2896         tp_g_signal_connect_object  (buffer, "changed",
2897                           G_CALLBACK (chat_input_text_buffer_changed_cb),
2898                           chat, 0);
2899         tp_g_signal_connect_object (priv->gsettings_chat,
2900                         "changed::" EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED,
2901                         G_CALLBACK (conf_spell_checking_cb), chat, 0);
2902         conf_spell_checking_cb (priv->gsettings_chat,
2903                                 EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED, chat);
2904         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_input),
2905                            chat->input_text_view);
2906         gtk_widget_show (chat->input_text_view);
2907
2908         /* Add the (invisible) search bar */
2909         priv->search_bar = empathy_search_bar_new (chat->view);
2910         gtk_box_pack_start (GTK_BOX(priv->vbox_left),
2911                             priv->search_bar,
2912                             FALSE, FALSE, 0);
2913         gtk_box_reorder_child (GTK_BOX(priv->vbox_left), priv->search_bar, 1);
2914
2915         /* Initialy hide the topic, will be shown if not empty */
2916         gtk_widget_hide (priv->hbox_topic);
2917
2918         g_signal_connect (priv->hpaned, "notify::position",
2919                           G_CALLBACK (chat_hpaned_pos_changed_cb),
2920                           chat);
2921
2922         /* Load the paned position */
2923         paned_pos = g_settings_get_int (priv->gsettings_ui,
2924                         EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS);
2925         if (paned_pos != 0)
2926                 gtk_paned_set_position (GTK_PANED(priv->hpaned), paned_pos);
2927
2928         /* Set widget focus order */
2929         list = g_list_append (NULL, priv->search_bar);
2930         list = g_list_append (list, priv->scrolled_window_input);
2931         gtk_container_set_focus_chain (GTK_CONTAINER (priv->vbox_left), list);
2932         g_list_free (list);
2933
2934         list = g_list_append (NULL, priv->vbox_left);
2935         list = g_list_append (list, priv->scrolled_window_contacts);
2936         gtk_container_set_focus_chain (GTK_CONTAINER (priv->hpaned), list);
2937         g_list_free (list);
2938
2939         list = g_list_append (NULL, priv->hpaned);
2940         list = g_list_append (list, priv->hbox_topic);
2941         gtk_container_set_focus_chain (GTK_CONTAINER (priv->widget), list);
2942         g_list_free (list);
2943
2944         /* Add the main widget in the chat widget */
2945         gtk_container_add (GTK_CONTAINER (chat), priv->widget);
2946         g_object_unref (gui);
2947 }
2948
2949 static void
2950 chat_size_allocate (GtkWidget     *widget,
2951                     GtkAllocation *allocation)
2952 {
2953   GtkBin *bin = GTK_BIN (widget);
2954   GtkAllocation child_allocation;
2955   GtkWidget *child;
2956
2957   gtk_widget_set_allocation (widget, allocation);
2958
2959   child = gtk_bin_get_child (bin);
2960
2961   if (child && gtk_widget_get_visible (child))
2962     {
2963       child_allocation.x = allocation->x + gtk_container_get_border_width (GTK_CONTAINER (widget));
2964       child_allocation.y = allocation->y + gtk_container_get_border_width (GTK_CONTAINER (widget));
2965       child_allocation.width = MAX (allocation->width - gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2, 0);
2966       child_allocation.height = MAX (allocation->height - gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2, 0);
2967
2968       gtk_widget_size_allocate (child, &child_allocation);
2969     }
2970 }
2971
2972 static void
2973 chat_finalize (GObject *object)
2974 {
2975         EmpathyChat     *chat;
2976         EmpathyChatPriv *priv;
2977
2978         chat = EMPATHY_CHAT (object);
2979         priv = GET_PRIV (chat);
2980
2981         DEBUG ("Finalized: %p", object);
2982
2983         if (priv->update_misspelled_words_id != 0)
2984                 g_source_remove (priv->update_misspelled_words_id);
2985
2986         if (priv->save_paned_pos_id != 0)
2987                 g_source_remove (priv->save_paned_pos_id);
2988
2989         g_object_unref (priv->gsettings_chat);
2990         g_object_unref (priv->gsettings_ui);
2991
2992         g_list_foreach (priv->input_history, (GFunc) chat_input_history_entry_free, NULL);
2993         g_list_free (priv->input_history);
2994
2995         g_list_foreach (priv->compositors, (GFunc) g_object_unref, NULL);
2996         g_list_free (priv->compositors);
2997
2998         chat_composing_remove_timeout (chat);
2999
3000         g_object_unref (priv->account_manager);
3001         g_object_unref (priv->log_manager);
3002
3003         if (priv->tp_chat) {
3004                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3005                         chat_invalidated_cb, chat);
3006                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3007                         chat_message_received_cb, chat);
3008                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3009                         chat_message_acknowledged_cb, chat);
3010                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3011                         chat_send_error_cb, chat);
3012                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3013                         chat_state_changed_cb, chat);
3014                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3015                         chat_property_changed_cb, chat);
3016                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3017                         chat_members_changed_cb, chat);
3018                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3019                         chat_remote_contact_changed_cb, chat);
3020                 empathy_tp_chat_leave (priv->tp_chat, "");
3021                 g_object_unref (priv->tp_chat);
3022         }
3023         if (priv->account) {
3024                 g_object_unref (priv->account);
3025         }
3026         if (priv->remote_contact) {
3027                 g_object_unref (priv->remote_contact);
3028         }
3029
3030         if (priv->block_events_timeout_id) {
3031                 g_source_remove (priv->block_events_timeout_id);
3032         }
3033
3034         g_free (priv->id);
3035         g_free (priv->name);
3036         g_free (priv->subject);
3037         g_completion_free (priv->completion);
3038
3039         G_OBJECT_CLASS (empathy_chat_parent_class)->finalize (object);
3040 }
3041
3042 static void
3043 chat_constructed (GObject *object)
3044 {
3045         EmpathyChat *chat = EMPATHY_CHAT (object);
3046         EmpathyChatPriv *priv = GET_PRIV (chat);
3047
3048         if (priv->handle_type != TP_HANDLE_TYPE_ROOM) {
3049                 /* First display logs from the logger and then display pending messages */
3050                 chat_add_logs (chat);
3051         }
3052          else {
3053                 /* Just display pending messages for rooms */
3054                 priv->can_show_pending = TRUE;
3055                 show_pending_messages (chat);
3056         }
3057 }
3058
3059 static void
3060 empathy_chat_class_init (EmpathyChatClass *klass)
3061 {
3062         GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
3063         GObjectClass   *object_class = G_OBJECT_CLASS (klass);
3064
3065         object_class->finalize = chat_finalize;
3066         object_class->get_property = chat_get_property;
3067         object_class->set_property = chat_set_property;
3068         object_class->constructed = chat_constructed;
3069
3070         widget_class->size_allocate = chat_size_allocate;
3071
3072         g_object_class_install_property (object_class,
3073                                          PROP_TP_CHAT,
3074                                          g_param_spec_object ("tp-chat",
3075                                                               "Empathy tp chat",
3076                                                               "The tp chat object",
3077                                                               EMPATHY_TYPE_TP_CHAT,
3078                                                               G_PARAM_CONSTRUCT |
3079                                                               G_PARAM_READWRITE |
3080                                                               G_PARAM_STATIC_STRINGS));
3081         g_object_class_install_property (object_class,
3082                                          PROP_ACCOUNT,
3083                                          g_param_spec_object ("account",
3084                                                               "Account of the chat",
3085                                                               "The account of the chat",
3086                                                               TP_TYPE_ACCOUNT,
3087                                                               G_PARAM_READABLE |
3088                                                               G_PARAM_STATIC_STRINGS));
3089         g_object_class_install_property (object_class,
3090                                          PROP_ID,
3091                                          g_param_spec_string ("id",
3092                                                               "Chat's id",
3093                                                               "The id of the chat",
3094                                                               NULL,
3095                                                               G_PARAM_READABLE |
3096                                                               G_PARAM_STATIC_STRINGS));
3097         g_object_class_install_property (object_class,
3098                                          PROP_NAME,
3099                                          g_param_spec_string ("name",
3100                                                               "Chat's name",
3101                                                               "The name of the chat",
3102                                                               NULL,
3103                                                               G_PARAM_READABLE |
3104                                                               G_PARAM_STATIC_STRINGS));
3105         g_object_class_install_property (object_class,
3106                                          PROP_SUBJECT,
3107                                          g_param_spec_string ("subject",
3108                                                               "Chat's subject",
3109                                                               "The subject or topic of the chat",
3110                                                               NULL,
3111                                                               G_PARAM_READABLE |
3112                                                               G_PARAM_STATIC_STRINGS));
3113         g_object_class_install_property (object_class,
3114                                          PROP_REMOTE_CONTACT,
3115                                          g_param_spec_object ("remote-contact",
3116                                                               "The remote contact",
3117                                                               "The remote contact is any",
3118                                                               EMPATHY_TYPE_CONTACT,
3119                                                               G_PARAM_READABLE |
3120                                                               G_PARAM_STATIC_STRINGS));
3121         g_object_class_install_property (object_class,
3122                                          PROP_SHOW_CONTACTS,
3123                                          g_param_spec_boolean ("show-contacts",
3124                                                                "Contacts' visibility",
3125                                                                "The visibility of the contacts' list",
3126                                                                TRUE,
3127                                                                G_PARAM_READWRITE |
3128                                                                G_PARAM_STATIC_STRINGS));
3129
3130         g_object_class_install_property (object_class,
3131                                          PROP_SMS_CHANNEL,
3132                                          g_param_spec_boolean ("sms-channel",
3133                                                                "SMS Channel",
3134                                                                "TRUE if this channel is for sending SMSes",
3135                                                                FALSE,
3136                                                                G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
3137
3138         g_object_class_install_property (object_class,
3139                                          PROP_N_MESSAGES_SENDING,
3140                                          g_param_spec_uint ("n-messages-sending",
3141                                                             "Num Messages Sending",
3142                                                             "The number of messages being sent",
3143                                                             0, G_MAXUINT, 0,
3144                                                             G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
3145
3146         g_object_class_install_property (object_class,
3147                                          PROP_NB_UNREAD_MESSAGES,
3148                                          g_param_spec_uint ("nb-unread-messages",
3149                                                             "Num Unread Messages",
3150                                                             "The number of unread messages",
3151                                                             0, G_MAXUINT, 0,
3152                                                             G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
3153
3154         signals[COMPOSING] =
3155                 g_signal_new ("composing",
3156                               G_OBJECT_CLASS_TYPE (object_class),
3157                               G_SIGNAL_RUN_LAST,
3158                               0,
3159                               NULL, NULL,
3160                               g_cclosure_marshal_VOID__BOOLEAN,
3161                               G_TYPE_NONE,
3162                               1, G_TYPE_BOOLEAN);
3163
3164         signals[NEW_MESSAGE] =
3165                 g_signal_new ("new-message",
3166                               G_OBJECT_CLASS_TYPE (object_class),
3167                               G_SIGNAL_RUN_LAST,
3168                               0,
3169                               NULL, NULL,
3170                               _empathy_gtk_marshal_VOID__OBJECT_BOOLEAN,
3171                               G_TYPE_NONE,
3172                               2, EMPATHY_TYPE_MESSAGE, G_TYPE_BOOLEAN);
3173
3174         signals[PART_COMMAND_ENTERED] =
3175                         g_signal_new ("part-command-entered",
3176                                   G_OBJECT_CLASS_TYPE (object_class),
3177                                   G_SIGNAL_RUN_LAST,
3178                                   0,
3179                                   NULL, NULL,
3180                                   g_cclosure_marshal_VOID__POINTER,
3181                                   G_TYPE_NONE,
3182                                   1, G_TYPE_STRV);
3183
3184         g_type_class_add_private (object_class, sizeof (EmpathyChatPriv));
3185 }
3186
3187 static gboolean
3188 chat_block_events_timeout_cb (gpointer data)
3189 {
3190         EmpathyChatPriv *priv = GET_PRIV (data);
3191
3192         priv->block_events_timeout_id = 0;
3193
3194         return FALSE;
3195 }
3196
3197 static void
3198 account_manager_prepared_cb (GObject *source_object,
3199                              GAsyncResult *result,
3200                              gpointer user_data)
3201 {
3202         GList *accounts, *l;
3203         TpAccountManager *account_manager = TP_ACCOUNT_MANAGER (source_object);
3204         EmpathyChat *chat = user_data;
3205         GError *error = NULL;
3206
3207         if (!tp_account_manager_prepare_finish (account_manager, result, &error)) {
3208                 DEBUG ("Failed to prepare the account manager: %s", error->message);
3209                 g_error_free (error);
3210                 return;
3211         }
3212
3213         accounts = tp_account_manager_get_valid_accounts (account_manager);
3214
3215         for (l = accounts; l != NULL; l = l->next) {
3216                 TpAccount *account = l->data;
3217                 tp_g_signal_connect_object (account, "status-changed",
3218                                              G_CALLBACK (chat_new_connection_cb),
3219                                              chat, 0);
3220         }
3221
3222         g_list_free (accounts);
3223 }
3224
3225 static void
3226 empathy_chat_init (EmpathyChat *chat)
3227 {
3228         EmpathyChatPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chat,
3229                 EMPATHY_TYPE_CHAT, EmpathyChatPriv);
3230
3231         chat->priv = priv;
3232         priv->log_manager = tpl_log_manager_dup_singleton ();
3233         priv->gsettings_chat = g_settings_new (EMPATHY_PREFS_CHAT_SCHEMA);
3234         priv->gsettings_ui = g_settings_new (EMPATHY_PREFS_UI_SCHEMA);
3235
3236         priv->contacts_width = -1;
3237         priv->input_history = NULL;
3238         priv->input_history_current = NULL;
3239         priv->account_manager = tp_account_manager_dup ();
3240
3241         tp_account_manager_prepare_async (priv->account_manager, NULL,
3242                                           account_manager_prepared_cb, chat);
3243
3244         priv->show_contacts = g_settings_get_boolean (priv->gsettings_chat,
3245                         EMPATHY_PREFS_CHAT_SHOW_CONTACTS_IN_ROOMS);
3246
3247         /* Block events for some time to avoid having "has come online" or
3248          * "joined" messages. */
3249         priv->block_events_timeout_id =
3250                 g_timeout_add_seconds (1, chat_block_events_timeout_cb, chat);
3251
3252         /* Add nick name completion */
3253         priv->completion = g_completion_new ((GCompletionFunc) empathy_contact_get_alias);
3254         g_completion_set_compare (priv->completion, chat_contacts_completion_func);
3255
3256         chat_create_ui (chat);
3257 }
3258
3259 EmpathyChat *
3260 empathy_chat_new (EmpathyTpChat *tp_chat)
3261 {
3262         return g_object_new (EMPATHY_TYPE_CHAT, "tp-chat", tp_chat, NULL);
3263 }
3264
3265 EmpathyTpChat *
3266 empathy_chat_get_tp_chat (EmpathyChat *chat)
3267 {
3268         EmpathyChatPriv *priv = GET_PRIV (chat);
3269
3270         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3271
3272         return priv->tp_chat;
3273 }
3274
3275 typedef struct
3276 {
3277         EmpathyChat *self;
3278         GtkWidget *info_bar;
3279         gulong response_id;
3280         GtkWidget *button;
3281         GtkWidget *label;
3282         GtkWidget *entry;
3283         GtkWidget *spinner;
3284         gchar *password;
3285 } PasswordData;
3286
3287 static void
3288 passwd_remember_button_cb (GtkButton *button,
3289                           PasswordData *data)
3290 {
3291         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3292 }
3293
3294 static void
3295 passwd_not_now_button_cb (GtkButton *button,
3296                           PasswordData *data)
3297 {
3298         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_NO);
3299 }
3300
3301 static void
3302 remember_password_infobar_response_cb (GtkWidget *info_bar,
3303                                        gint response_id,
3304                                        PasswordData *data)
3305 {
3306         EmpathyChatPriv *priv = GET_PRIV (data->self);
3307
3308         if (response_id == GTK_RESPONSE_OK) {
3309                 DEBUG ("Saving room password");
3310                 empathy_keyring_set_room_password_async (priv->account,
3311                                                          empathy_tp_chat_get_id (priv->tp_chat),
3312                                                          data->password,
3313                                                          NULL, NULL);
3314         }
3315
3316         gtk_widget_destroy (info_bar);
3317         g_free (data->password);
3318         g_slice_free (PasswordData, data);
3319 }
3320
3321 static void
3322 chat_prompt_to_save_password (EmpathyChat *self,
3323                               PasswordData *data)
3324 {
3325         GtkWidget *content_area;
3326         GtkWidget *hbox;
3327         GtkWidget *image;
3328         GtkWidget *label;
3329         GtkWidget *alig;
3330         GtkWidget *button;
3331
3332         /* save the password in case it needs to be saved */
3333         data->password = g_strdup (gtk_entry_get_text (GTK_ENTRY (data->entry)));
3334
3335         /* Remove all previous widgets */
3336         content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (data->info_bar));
3337         gtk_container_forall (GTK_CONTAINER (content_area),
3338                               (GtkCallback) gtk_widget_destroy, NULL);
3339         data->button = NULL;
3340         data->label = NULL;
3341         data->entry = NULL;
3342         data->spinner = NULL;
3343
3344         gtk_info_bar_set_message_type (GTK_INFO_BAR (data->info_bar),
3345                                        GTK_MESSAGE_QUESTION);
3346
3347         hbox = gtk_hbox_new (FALSE, 5);
3348         gtk_box_pack_start (GTK_BOX (content_area), hbox, TRUE, TRUE, 0);
3349
3350         /* Add image */
3351         image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_AUTHENTICATION,
3352                                           GTK_ICON_SIZE_DIALOG);
3353         gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
3354
3355         /* Add message */
3356         label = gtk_label_new (_("Would you like to store this password?"));
3357         gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0);
3358
3359         /* Add 'Remember' button */
3360         alig = gtk_alignment_new (0, 0.5, 1, 0);
3361
3362         button = gtk_button_new_with_label (_("Remember"));
3363         gtk_container_add (GTK_CONTAINER (alig), button);
3364         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3365
3366         g_signal_connect (button, "clicked", G_CALLBACK (passwd_remember_button_cb),
3367                           data);
3368
3369         /* Add 'Not now' button */
3370         alig = gtk_alignment_new (0, 0.5, 1, 0);
3371
3372         button = gtk_button_new_with_label (_("Not now"));
3373         gtk_container_add (GTK_CONTAINER (alig), button);
3374         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3375
3376         g_signal_connect (button, "clicked", G_CALLBACK (passwd_not_now_button_cb),
3377                           data);
3378
3379         /* go! */
3380         g_signal_handler_disconnect (data->info_bar, data->response_id);
3381         g_signal_connect (data->info_bar, "response",
3382                           G_CALLBACK (remember_password_infobar_response_cb), data);
3383
3384         gtk_widget_show_all (data->info_bar);
3385 }
3386
3387 static void
3388 provide_password_cb (GObject *tp_chat,
3389                      GAsyncResult *res,
3390                      gpointer user_data)
3391 {
3392         PasswordData *data = user_data;
3393         EmpathyChat *self = data->self;
3394         EmpathyChatPriv *priv = GET_PRIV (self);
3395         GError *error = NULL;
3396
3397         if (!empathy_tp_chat_provide_password_finish (EMPATHY_TP_CHAT (tp_chat), res,
3398                                                       &error)) {
3399                 DEBUG ("error: %s", error->message);
3400                 /* FIXME: what should we do if that's another error? Close the channel?
3401                  * Display the raw D-Bus error to the user isn't very useful */
3402                 if (g_error_matches (error, TP_ERRORS, TP_ERROR_AUTHENTICATION_FAILED)) {
3403                         /* entry */
3404                         gtk_entry_set_text (GTK_ENTRY (data->entry), "");
3405                         gtk_widget_set_sensitive (data->entry, TRUE);
3406                         gtk_widget_grab_focus (data->entry);
3407
3408                         /* info bar */
3409                         gtk_info_bar_set_message_type (
3410                             GTK_INFO_BAR (data->info_bar),
3411                             GTK_MESSAGE_ERROR);
3412
3413                         /* button */
3414                         gtk_widget_set_sensitive (data->button, TRUE);
3415                         gtk_button_set_label (GTK_BUTTON (data->button),
3416                             _("Retry"));
3417
3418                         /* label */
3419                         gtk_label_set_text (GTK_LABEL (data->label),
3420                             _("Wrong password; please try again:"));
3421
3422                         /* spinner */
3423                         gtk_spinner_stop (GTK_SPINNER (data->spinner));
3424                         gtk_widget_hide (data->spinner);
3425                 }
3426                 g_error_free (error);
3427                 return;
3428         }
3429
3430         if (empathy_keyring_is_available ()) {
3431                 /* ask whether they want to save the password */
3432                 chat_prompt_to_save_password (self, data);
3433         } else {
3434                 /* Get rid of the password info bar finally */
3435                 gtk_widget_destroy (data->info_bar);
3436                 g_slice_free (PasswordData, data);
3437         }
3438
3439         /* Room joined */
3440         gtk_widget_set_sensitive (priv->hpaned, TRUE);
3441         gtk_widget_set_sensitive (self->input_text_view, TRUE);
3442         gtk_widget_grab_focus (self->input_text_view);
3443 }
3444
3445 static void
3446 password_infobar_response_cb (GtkWidget *info_bar,
3447                               gint response_id,
3448                               PasswordData *data)
3449 {
3450         EmpathyChatPriv *priv = GET_PRIV (data->self);
3451         const gchar *password;
3452
3453         if (response_id != GTK_RESPONSE_OK) {
3454                 gtk_widget_destroy (info_bar);
3455                 g_slice_free (PasswordData, data);
3456                 return;
3457         }
3458
3459         password = gtk_entry_get_text (GTK_ENTRY (data->entry));
3460
3461         empathy_tp_chat_provide_password_async (priv->tp_chat, password,
3462                                                 provide_password_cb, data);
3463
3464         gtk_widget_set_sensitive (data->button, FALSE);
3465         gtk_widget_set_sensitive (data->entry, FALSE);
3466
3467         gtk_spinner_start (GTK_SPINNER (data->spinner));
3468         gtk_widget_show (data->spinner);
3469 }
3470
3471 static void
3472 password_entry_activate_cb (GtkWidget *entry,
3473                           PasswordData *data)
3474 {
3475         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3476 }
3477
3478 static void
3479 passwd_join_button_cb (GtkButton *button,
3480                           PasswordData *data)
3481 {
3482         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3483 }
3484
3485 static void
3486 clear_icon_released_cb (GtkEntry *entry,
3487                         GtkEntryIconPosition icon_pos,
3488                         GdkEvent *event,
3489                         PasswordData *data)
3490 {
3491         gtk_entry_set_text (entry, "");
3492 }
3493
3494 static void
3495 password_entry_changed_cb (GtkEditable *entry,
3496                            PasswordData *data)
3497 {
3498         const gchar *str;
3499
3500         str = gtk_entry_get_text (GTK_ENTRY (entry));
3501
3502         gtk_entry_set_icon_sensitive (GTK_ENTRY (entry),
3503             GTK_ENTRY_ICON_SECONDARY, !EMP_STR_EMPTY (str));
3504 }
3505
3506 static void
3507 infobar_chat_invalidated_cb (TpProxy       *proxy,
3508                            guint          domain,
3509                            gint           code,
3510                            gchar         *message,
3511                            gpointer       password_infobar)
3512 {
3513         /* Destroy the password infobar whenever a channel is invalidated
3514          * so we don't have multiple infobars when the MUC is rejoined */
3515         gtk_widget_destroy (GTK_WIDGET (password_infobar));
3516 }
3517
3518 static void
3519 display_password_info_bar (EmpathyChat *self)
3520 {
3521         EmpathyChatPriv *priv = GET_PRIV (self);
3522         GtkWidget *info_bar;
3523         GtkWidget *content_area;
3524         GtkWidget *hbox;
3525         GtkWidget *image;
3526         GtkWidget *label;
3527         GtkWidget *entry;
3528         GtkWidget *alig;
3529         GtkWidget *button;
3530         GtkWidget *spinner;
3531         PasswordData *data;
3532
3533         data = g_slice_new0 (PasswordData);
3534
3535         info_bar = gtk_info_bar_new ();
3536         gtk_info_bar_set_message_type (GTK_INFO_BAR (info_bar),
3537             GTK_MESSAGE_QUESTION);
3538
3539         content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (info_bar));
3540
3541         hbox = gtk_hbox_new (FALSE, 5);
3542         gtk_box_pack_start (GTK_BOX (content_area), hbox, TRUE, TRUE, 0);
3543
3544         /* Add image */
3545         image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_AUTHENTICATION,
3546                                           GTK_ICON_SIZE_DIALOG);
3547         gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
3548
3549         /* Add message */
3550         label = gtk_label_new (_("This room is protected by a password:"));
3551         gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);
3552
3553         /* Add password entry */
3554         entry = gtk_entry_new ();
3555         gtk_entry_set_visibility (GTK_ENTRY (entry), FALSE);
3556         gtk_box_pack_start (GTK_BOX (hbox), entry, TRUE, TRUE, 0);
3557
3558         gtk_entry_set_icon_from_stock (GTK_ENTRY (entry),
3559                                        GTK_ENTRY_ICON_SECONDARY, GTK_STOCK_CLEAR);
3560         gtk_entry_set_icon_sensitive (GTK_ENTRY (entry),
3561                                       GTK_ENTRY_ICON_SECONDARY, FALSE);
3562
3563         g_signal_connect (entry, "icon-release",
3564                           G_CALLBACK (clear_icon_released_cb), data);
3565         g_signal_connect (entry, "changed",
3566                           G_CALLBACK (password_entry_changed_cb), data);
3567
3568         g_signal_connect (entry, "activate",
3569                           G_CALLBACK (password_entry_activate_cb), data);
3570
3571         /* Focus the password entry once it's realized */
3572         g_signal_connect (entry, "realize", G_CALLBACK (gtk_widget_grab_focus), NULL);
3573
3574         /* Add 'Join' button */
3575         alig = gtk_alignment_new (0, 0.5, 1, 0);
3576
3577         button = gtk_button_new_with_label (_("Join"));
3578         gtk_container_add (GTK_CONTAINER (alig), button);
3579         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3580
3581         g_signal_connect (button, "clicked", G_CALLBACK (passwd_join_button_cb),
3582                           data);
3583
3584         /* Add spinner */
3585         spinner = gtk_spinner_new ();
3586         gtk_box_pack_end (GTK_BOX (hbox), spinner, FALSE, FALSE, 0);
3587
3588         /* Save some data for messing around with later */
3589         data->self = self;
3590         data->info_bar = info_bar;
3591         data->button = button;
3592         data->label = label;
3593         data->entry = entry;
3594         data->spinner = spinner;
3595
3596         gtk_box_pack_start (GTK_BOX (priv->info_bar_vbox), info_bar,
3597                             TRUE, TRUE, 3);
3598         gtk_widget_show_all (hbox);
3599
3600         tp_g_signal_connect_object (priv->tp_chat,
3601                                   "invalidated", G_CALLBACK (infobar_chat_invalidated_cb),
3602                                   info_bar, 0);
3603
3604         data->response_id = g_signal_connect (info_bar, "response",
3605                                               G_CALLBACK (password_infobar_response_cb), data);
3606
3607         gtk_widget_show_all (info_bar);
3608         /* ... but hide the spinner */
3609         gtk_widget_hide (spinner);
3610
3611         /* prevent the user from typing anything */
3612         gtk_widget_set_sensitive (self->input_text_view, FALSE);
3613 }
3614
3615 static void
3616 provide_saved_password_cb (GObject *tp_chat,
3617                            GAsyncResult *res,
3618                            gpointer user_data)
3619 {
3620         EmpathyChat *self = user_data;
3621         EmpathyChatPriv *priv = GET_PRIV (self);
3622         GError *error = NULL;
3623
3624         if (!empathy_tp_chat_provide_password_finish (EMPATHY_TP_CHAT (tp_chat), res,
3625                                                       &error)) {
3626                 DEBUG ("error: %s", error->message);
3627                 /* FIXME: what should we do if that's another error? Close the channel?
3628                  * Display the raw D-Bus error to the user isn't very useful */
3629                 if (g_error_matches (error, TP_ERRORS, TP_ERROR_AUTHENTICATION_FAILED)) {
3630                         display_password_info_bar (self);
3631                         gtk_widget_set_sensitive (priv->hpaned, FALSE);
3632                 }
3633                 g_error_free (error);
3634                 return;
3635         }
3636
3637         /* Room joined */
3638         gtk_widget_set_sensitive (priv->hpaned, TRUE);
3639         gtk_widget_grab_focus (self->input_text_view);
3640 }
3641
3642 static void
3643 chat_room_got_password_cb (GObject *source,
3644                            GAsyncResult *result,
3645                            gpointer user_data)
3646 {
3647         EmpathyChat *self = user_data;
3648         EmpathyChatPriv *priv = GET_PRIV (self);
3649         const gchar *password;
3650         GError *error = NULL;
3651
3652         password = empathy_keyring_get_room_password_finish (priv->account,
3653             result, &error);
3654
3655         if (error != NULL) {
3656                 DEBUG ("Couldn't get room password: %s\n", error->message);
3657                 g_clear_error (&error);
3658
3659                 display_password_info_bar (self);
3660                 gtk_widget_set_sensitive (priv->hpaned, FALSE);
3661                 return;
3662         }
3663
3664         empathy_tp_chat_provide_password_async (priv->tp_chat, password,
3665                                                 provide_saved_password_cb, self);
3666 }
3667
3668 static void
3669 chat_password_needed_changed_cb (EmpathyChat *self)
3670 {
3671         EmpathyChatPriv *priv = GET_PRIV (self);
3672
3673         if (empathy_tp_chat_password_needed (priv->tp_chat)) {
3674                 empathy_keyring_get_room_password_async (priv->account,
3675                                                          empathy_tp_chat_get_id (priv->tp_chat),
3676                                                          chat_room_got_password_cb, self);
3677         }
3678 }
3679
3680 static void
3681 chat_sms_channel_changed_cb (EmpathyChat *self)
3682 {
3683         EmpathyChatPriv *priv = GET_PRIV (self);
3684
3685         priv->sms_channel = tp_text_channel_is_sms_channel (
3686                 (TpTextChannel *) priv->tp_chat);
3687         g_object_notify (G_OBJECT (self), "sms-channel");
3688 }
3689
3690 static void
3691 chat_n_messages_sending_changed_cb (EmpathyChat *self)
3692 {
3693         g_object_notify (G_OBJECT (self), "n-messages-sending");
3694 }
3695
3696 void
3697 empathy_chat_set_tp_chat (EmpathyChat   *chat,
3698                           EmpathyTpChat *tp_chat)
3699 {
3700         EmpathyChatPriv *priv = GET_PRIV (chat);
3701         GPtrArray       *properties;
3702
3703         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3704         g_return_if_fail (EMPATHY_IS_TP_CHAT (tp_chat));
3705
3706         if (priv->tp_chat) {
3707                 return;
3708         }
3709
3710         if (priv->account) {
3711                 g_object_unref (priv->account);
3712         }
3713
3714         priv->tp_chat = g_object_ref (tp_chat);
3715         priv->account = g_object_ref (empathy_tp_chat_get_account (priv->tp_chat));
3716
3717         g_signal_connect (tp_chat, "invalidated",
3718                           G_CALLBACK (chat_invalidated_cb),
3719                           chat);
3720         g_signal_connect (tp_chat, "message-received-empathy",
3721                           G_CALLBACK (chat_message_received_cb),
3722                           chat);
3723         g_signal_connect (tp_chat, "message_acknowledged",
3724                           G_CALLBACK (chat_message_acknowledged_cb),
3725                           chat);
3726         g_signal_connect (tp_chat, "send-error",
3727                           G_CALLBACK (chat_send_error_cb),
3728                           chat);
3729         g_signal_connect (tp_chat, "chat-state-changed-empathy",
3730                           G_CALLBACK (chat_state_changed_cb),
3731                           chat);
3732         g_signal_connect (tp_chat, "property-changed",
3733                           G_CALLBACK (chat_property_changed_cb),
3734                           chat);
3735         g_signal_connect (tp_chat, "members-changed",
3736                           G_CALLBACK (chat_members_changed_cb),
3737                           chat);
3738         g_signal_connect (tp_chat, "member-renamed",
3739                           G_CALLBACK (chat_member_renamed_cb),
3740                           chat);
3741         g_signal_connect_swapped (tp_chat, "notify::remote-contact",
3742                                   G_CALLBACK (chat_remote_contact_changed_cb),
3743                                   chat);
3744         g_signal_connect_swapped (tp_chat, "notify::password-needed",
3745                                   G_CALLBACK (chat_password_needed_changed_cb),
3746                                   chat);
3747         g_signal_connect_swapped (tp_chat, "notify::is-sms-channel",
3748                                   G_CALLBACK (chat_sms_channel_changed_cb),
3749                                   chat);
3750         g_signal_connect_swapped (tp_chat, "notify::n-messages-sending",
3751                                   G_CALLBACK (chat_n_messages_sending_changed_cb),
3752                                   chat);
3753
3754         /* Get initial value of properties */
3755         properties = empathy_tp_chat_get_properties (priv->tp_chat);
3756         if (properties != NULL) {
3757                 guint i;
3758
3759                 for (i = 0; i < properties->len; i++) {
3760                         EmpathyTpChatProperty *property;
3761
3762                         property = g_ptr_array_index (properties, i);
3763                         if (property->value == NULL)
3764                                 continue;
3765
3766                         chat_property_changed_cb (priv->tp_chat,
3767                                                   property->name,
3768                                                   property->value,
3769                                                   chat);
3770                 }
3771         }
3772
3773         chat_sms_channel_changed_cb (chat);
3774         chat_remote_contact_changed_cb (chat);
3775
3776         if (chat->input_text_view) {
3777                 gtk_widget_set_sensitive (chat->input_text_view, TRUE);
3778                 if (priv->block_events_timeout_id == 0) {
3779                         empathy_chat_view_append_event (chat->view, _("Connected"));
3780                 }
3781         }
3782
3783         g_object_notify (G_OBJECT (chat), "tp-chat");
3784         g_object_notify (G_OBJECT (chat), "id");
3785         g_object_notify (G_OBJECT (chat), "account");
3786
3787         /* This is a noop when tp-chat is set at object construction time and causes
3788          * the pending messages to be show when it's set on the object after it has
3789          * been created */
3790         show_pending_messages (chat);
3791
3792         /* check if a password is needed */
3793         chat_password_needed_changed_cb (chat);
3794 }
3795
3796 TpAccount *
3797 empathy_chat_get_account (EmpathyChat *chat)
3798 {
3799         EmpathyChatPriv *priv = GET_PRIV (chat);
3800
3801         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3802
3803         return priv->account;
3804 }
3805
3806 const gchar *
3807 empathy_chat_get_id (EmpathyChat *chat)
3808 {
3809         EmpathyChatPriv *priv = GET_PRIV (chat);
3810
3811         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3812
3813         return priv->id;
3814 }
3815
3816 gchar *
3817 empathy_chat_dup_name (EmpathyChat *chat)
3818 {
3819         EmpathyChatPriv *priv = GET_PRIV (chat);
3820         const gchar *ret;
3821
3822         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3823
3824         ret = priv->name;
3825
3826         if (!ret && priv->remote_contact) {
3827                 ret = empathy_contact_get_alias (priv->remote_contact);
3828         }
3829
3830         if (!ret)
3831                 ret = priv->id;
3832
3833         if (!ret)
3834                 ret = _("Conversation");
3835
3836         if (priv->sms_channel)
3837                 /* Translators: this string is a something like
3838                  * "Escher Cat (SMS)" */
3839                 return g_strdup_printf (_("%s (SMS)"), ret);
3840         else
3841                 return g_strdup (ret);
3842 }
3843
3844 const gchar *
3845 empathy_chat_get_subject (EmpathyChat *chat)
3846 {
3847         EmpathyChatPriv *priv = GET_PRIV (chat);
3848
3849         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3850
3851         return priv->subject;
3852 }
3853
3854 EmpathyContact *
3855 empathy_chat_get_remote_contact (EmpathyChat *chat)
3856 {
3857         EmpathyChatPriv *priv = GET_PRIV (chat);
3858
3859         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3860
3861         return priv->remote_contact;
3862 }
3863
3864 GtkWidget *
3865 empathy_chat_get_contact_menu (EmpathyChat *chat)
3866 {
3867         EmpathyChatPriv *priv = GET_PRIV (chat);
3868         GtkWidget       *menu = NULL;
3869
3870         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3871
3872         if (priv->remote_contact) {
3873                 menu = empathy_contact_menu_new (priv->remote_contact,
3874                                                  EMPATHY_CONTACT_FEATURE_CALL |
3875                                                  EMPATHY_CONTACT_FEATURE_LOG |
3876                                                  EMPATHY_CONTACT_FEATURE_INFO |
3877                                                  EMPATHY_CONTACT_FEATURE_BLOCK);
3878         }
3879
3880         return menu;
3881 }
3882
3883 void
3884 empathy_chat_clear (EmpathyChat *chat)
3885 {
3886         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3887
3888         empathy_chat_view_clear (chat->view);
3889 }
3890
3891 void
3892 empathy_chat_scroll_down (EmpathyChat *chat)
3893 {
3894         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3895
3896         empathy_chat_view_scroll_down (chat->view);
3897 }
3898
3899 void
3900 empathy_chat_cut (EmpathyChat *chat)
3901 {
3902         GtkTextBuffer *buffer;
3903
3904         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3905
3906         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3907         if (gtk_text_buffer_get_has_selection (buffer)) {
3908                 GtkClipboard *clipboard;
3909
3910                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3911
3912                 gtk_text_buffer_cut_clipboard (buffer, clipboard, TRUE);
3913         }
3914 }
3915
3916 void
3917 empathy_chat_copy (EmpathyChat *chat)
3918 {
3919         GtkTextBuffer *buffer;
3920
3921         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3922
3923         if (empathy_chat_view_get_has_selection (chat->view)) {
3924                 empathy_chat_view_copy_clipboard (chat->view);
3925                 return;
3926         }
3927
3928         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3929         if (gtk_text_buffer_get_has_selection (buffer)) {
3930                 GtkClipboard *clipboard;
3931
3932                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3933
3934                 gtk_text_buffer_copy_clipboard (buffer, clipboard);
3935         }
3936         else {
3937                 gint start_offset;
3938                 gint end_offset;
3939                 EmpathyChatPriv *priv = GET_PRIV (chat);
3940
3941                 if (gtk_label_get_selection_bounds (GTK_LABEL (priv->label_topic),
3942                                                                &start_offset,
3943                                                                &end_offset)) {
3944                         gchar *start;
3945                         gchar *end;
3946                         gchar *selection;
3947                         const gchar *topic;
3948                         GtkClipboard *clipboard;
3949
3950                         topic = gtk_label_get_text (GTK_LABEL (priv->label_topic));
3951                         start = g_utf8_offset_to_pointer (topic, start_offset);
3952                         end = g_utf8_offset_to_pointer (topic, end_offset);
3953                         selection = g_strndup (start, end - start);
3954
3955                         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3956                         gtk_clipboard_set_text (clipboard, selection, -1);
3957
3958                         g_free (selection);
3959                 }
3960         }
3961 }
3962
3963 void
3964 empathy_chat_paste (EmpathyChat *chat)
3965 {
3966         GtkTextBuffer *buffer;
3967         GtkClipboard  *clipboard;
3968         EmpathyChatPriv *priv;
3969
3970         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3971
3972         priv = GET_PRIV (chat);
3973
3974         if (gtk_widget_get_visible (priv->search_bar)) {
3975                 empathy_search_bar_paste_clipboard (EMPATHY_SEARCH_BAR (priv->search_bar));
3976                 return;
3977         }
3978
3979         if (priv->tp_chat == NULL ||
3980             !gtk_widget_is_sensitive (chat->input_text_view))
3981                 return;
3982
3983         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3984         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3985
3986         gtk_text_buffer_paste_clipboard (buffer, clipboard, NULL, TRUE);
3987 }
3988
3989 void
3990 empathy_chat_find (EmpathyChat *chat)
3991 {
3992         EmpathyChatPriv *priv;
3993
3994         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3995
3996         priv = GET_PRIV (chat);
3997
3998         empathy_search_bar_show (EMPATHY_SEARCH_BAR (priv->search_bar));
3999 }
4000
4001 void
4002 empathy_chat_correct_word (EmpathyChat  *chat,
4003                           GtkTextIter *start,
4004                           GtkTextIter *end,
4005                           const gchar *new_word)
4006 {
4007         GtkTextBuffer *buffer;
4008
4009         g_return_if_fail (chat != NULL);
4010         g_return_if_fail (new_word != NULL);
4011
4012         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
4013
4014         gtk_text_buffer_delete (buffer, start, end);
4015         gtk_text_buffer_insert (buffer, start,
4016                                 new_word,
4017                                 -1);
4018 }
4019
4020 gboolean
4021 empathy_chat_is_room (EmpathyChat *chat)
4022 {
4023         EmpathyChatPriv *priv = GET_PRIV (chat);
4024
4025         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
4026
4027         return (priv->handle_type == TP_HANDLE_TYPE_ROOM);
4028 }
4029
4030 guint
4031 empathy_chat_get_nb_unread_messages (EmpathyChat *self)
4032 {
4033         EmpathyChatPriv *priv = GET_PRIV (self);
4034
4035         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
4036
4037         return priv->unread_messages;
4038 }
4039
4040 /* called when the messages have been read by user */
4041 void
4042 empathy_chat_messages_read (EmpathyChat *self)
4043 {
4044         EmpathyChatPriv *priv = GET_PRIV (self);
4045
4046         g_return_if_fail (EMPATHY_IS_CHAT (self));
4047
4048         /* FIXME: See Bug#610994, See comments about it in EmpathyChatPriv
4049          * definition. If we are still retrieving the backlogs, do not ACK */
4050         if (priv->retrieving_backlogs)
4051                 return;
4052
4053         if (priv->tp_chat != NULL) {
4054                 empathy_tp_chat_acknowledge_all_messages (priv->tp_chat);
4055         }
4056 }
4057
4058 /* Return TRUE if on of the contacts in this chat is composing */
4059 gboolean
4060 empathy_chat_is_composing (EmpathyChat *chat)
4061 {
4062   return chat->priv->compositors != NULL;
4063 }
4064
4065 gboolean
4066 empathy_chat_is_sms_channel (EmpathyChat *self)
4067 {
4068         EmpathyChatPriv *priv = GET_PRIV (self);
4069
4070         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
4071
4072         return priv->sms_channel;
4073 }
4074
4075 guint
4076 empathy_chat_get_n_messages_sending (EmpathyChat *self)
4077 {
4078         EmpathyChatPriv *priv;
4079
4080         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
4081
4082         priv = GET_PRIV (self);
4083
4084         if (priv->tp_chat == NULL) {
4085                 return 0;
4086         } else {
4087                 guint n_messages;
4088
4089                 g_object_get (priv->tp_chat,
4090                         "n-messages-sending", &n_messages,
4091                         NULL);
4092
4093                 return n_messages;
4094         }
4095 }
4096
4097 gchar *
4098 empathy_chat_dup_text (EmpathyChat *self)
4099 {
4100         GtkTextBuffer *buffer;
4101         GtkTextIter     start, end;
4102
4103         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (self->input_text_view));
4104
4105         gtk_text_buffer_get_bounds (buffer, &start, &end);
4106         return gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
4107 }
4108
4109 void
4110 empathy_chat_set_text (EmpathyChat *self,
4111                        const gchar *text)
4112 {
4113         GtkTextBuffer *buffer;
4114
4115         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (self->input_text_view));
4116
4117         gtk_text_buffer_set_text (buffer, text, -1);
4118 }