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