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