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