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