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