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