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