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