]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-chat.c
contact-list-store: don't put contacts in 'Ungrouped' when show-groups = False
[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-2008 Collabora Ltd.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation; either version 2 of the
9  * License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public
17  * License along with this program; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA  02110-1301  USA
20  *
21  * Authors: Mikael Hallendal <micke@imendio.com>
22  *          Richard Hult <richard@imendio.com>
23  *          Martyn Russell <martyn@imendio.com>
24  *          Geert-Jan Van den Bogaerde <geertjan@gnome.org>
25  *          Xavier Claessens <xclaesse@gmail.com>
26  */
27
28 #include <config.h>
29
30 #include <string.h>
31 #include <stdlib.h>
32
33 #include <gdk/gdkkeysyms.h>
34 #include <glib/gi18n-lib.h>
35 #include <gtk/gtk.h>
36
37 #include <telepathy-glib/account-manager.h>
38 #include <telepathy-glib/util.h>
39 #ifdef ENABLE_TPL
40 #include <telepathy-logger/log-manager.h>
41 #else
42
43 #include <libempathy/empathy-log-manager.h>
44 #endif /* ENABLE_TPL */
45 #include <libempathy/empathy-contact-list.h>
46 #include <libempathy/empathy-utils.h>
47 #include <libempathy/empathy-dispatcher.h>
48
49 #include "empathy-chat.h"
50 #include "empathy-conf.h"
51 #include "empathy-spell.h"
52 #include "empathy-contact-list-store.h"
53 #include "empathy-contact-list-view.h"
54 #include "empathy-contact-menu.h"
55 #include "empathy-search-bar.h"
56 #include "empathy-theme-manager.h"
57 #include "empathy-smiley-manager.h"
58 #include "empathy-ui-utils.h"
59 #include "empathy-string-parser.h"
60
61 #define DEBUG_FLAG EMPATHY_DEBUG_CHAT
62 #include <libempathy/empathy-debug.h>
63
64 #define CHAT_DIR_CREATE_MODE  (S_IRUSR | S_IWUSR | S_IXUSR)
65 #define CHAT_FILE_CREATE_MODE (S_IRUSR | S_IWUSR)
66 #define IS_ENTER(v) (v == GDK_Return || v == GDK_ISO_Enter || v == GDK_KP_Enter)
67 #define MAX_INPUT_HEIGHT 150
68 #define COMPOSING_STOP_TIMEOUT 5
69
70 #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyChat)
71 typedef struct {
72         EmpathyTpChat     *tp_chat;
73         TpAccount         *account;
74         gchar             *id;
75         gchar             *name;
76         gchar             *subject;
77         EmpathyContact    *remote_contact;
78         gboolean           show_contacts;
79
80 #ifdef ENABLE_TPL
81         TplLogManager     *log_manager;
82 #else
83         EmpathyLogManager *log_manager;
84 #endif /* ENABLE_TPL */
85         TpAccountManager  *account_manager;
86         GList             *input_history;
87         GList             *input_history_current;
88         GList             *compositors;
89         GCompletion       *completion;
90         guint              composing_stop_timeout_id;
91         guint              block_events_timeout_id;
92         TpHandleType       handle_type;
93         gint               contacts_width;
94         gboolean           has_input_vscroll;
95
96         GtkWidget         *widget;
97         GtkWidget         *hpaned;
98         GtkWidget         *vbox_left;
99         GtkWidget         *scrolled_window_chat;
100         GtkWidget         *scrolled_window_input;
101         GtkWidget         *scrolled_window_contacts;
102         GtkWidget         *hbox_topic;
103         GtkWidget         *label_topic;
104         GtkWidget         *contact_list_view;
105         GtkWidget         *info_bar_vbox;
106         GtkWidget         *search_bar;
107
108         guint              unread_messages;
109         /* TRUE if the pending messages can be displayed. This is to avoid to show
110          * pending messages *before* messages from logs. (#603980) */
111         gboolean           can_show_pending;
112
113         /* FIXME: retrieving_backlogs flag is a workaround for Bug#610994 and should
114          * be differently handled since it introduces another race condition, which
115          * is really hard to occur, but still possible.
116          *
117          * With the current workaround (which has the race above), we need to be
118          * sure to ACK any pending messages only when the retrieval of backlogs is
119          * finished, that's why using retrieving_backlogs flag.
120          * empathy_chat_messages_read () will check this variable and not ACK
121          * anything when TRUE. It will be set TRUE at chat_constructed () and set
122          * back to FALSE when the backlog has been retrieved and the pending
123          * messages actually showed to the user.
124          *
125          * Race condition introduced with this workaround:
126          * Scenario: a message is pending, the user is notified and selects the tab.
127          * the tab with a pending message is focused before the messages are properly
128          * shown (since the preparation of the window is slower AND async WRT the
129          * tab showing), which means the user won't see any new messages (rare but
130          * possible), if he/she will change tab focus before the messages are
131          * properly shown, the tab will be set as 'seen' and the user won't be
132          * notified again about the already notified pending messages when the
133          * messages in tab will be properly shown */
134         gboolean           retrieving_backlogs;
135 } EmpathyChatPriv;
136
137 typedef struct {
138         gchar *text; /* Original message that was specified
139                       * upon entry creation. */
140         gchar *modified_text; /* Message that was modified by user.
141                                * When no modifications were made, it is NULL */
142 } InputHistoryEntry;
143
144 enum {
145         COMPOSING,
146         NEW_MESSAGE,
147         LAST_SIGNAL
148 };
149
150 enum {
151         PROP_0,
152         PROP_TP_CHAT,
153         PROP_ACCOUNT,
154         PROP_ID,
155         PROP_NAME,
156         PROP_SUBJECT,
157         PROP_REMOTE_CONTACT,
158         PROP_SHOW_CONTACTS,
159 };
160
161 static guint signals[LAST_SIGNAL] = { 0 };
162
163 G_DEFINE_TYPE (EmpathyChat, empathy_chat, GTK_TYPE_BIN);
164
165 static void
166 chat_get_property (GObject    *object,
167                    guint       param_id,
168                    GValue     *value,
169                    GParamSpec *pspec)
170 {
171         EmpathyChat *chat = EMPATHY_CHAT (object);
172         EmpathyChatPriv *priv = GET_PRIV (object);
173
174         switch (param_id) {
175         case PROP_TP_CHAT:
176                 g_value_set_object (value, priv->tp_chat);
177                 break;
178         case PROP_ACCOUNT:
179                 g_value_set_object (value, priv->account);
180                 break;
181         case PROP_NAME:
182                 g_value_set_string (value, empathy_chat_get_name (chat));
183                 break;
184         case PROP_ID:
185                 g_value_set_string (value, priv->id);
186                 break;
187         case PROP_SUBJECT:
188                 g_value_set_string (value, priv->subject);
189                 break;
190         case PROP_REMOTE_CONTACT:
191                 g_value_set_object (value, priv->remote_contact);
192                 break;
193         case PROP_SHOW_CONTACTS:
194                 g_value_set_boolean (value, priv->show_contacts);
195                 break;
196         default:
197                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
198                 break;
199         };
200 }
201
202 static void
203 chat_set_property (GObject      *object,
204                    guint         param_id,
205                    const GValue *value,
206                    GParamSpec   *pspec)
207 {
208         EmpathyChat *chat = EMPATHY_CHAT (object);
209
210         switch (param_id) {
211         case PROP_TP_CHAT:
212                 empathy_chat_set_tp_chat (chat, EMPATHY_TP_CHAT (g_value_get_object (value)));
213                 break;
214         case PROP_SHOW_CONTACTS:
215                 empathy_chat_set_show_contacts (chat, g_value_get_boolean (value));
216                 break;
217         default:
218                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
219                 break;
220         };
221 }
222
223 static void
224 chat_connect_channel_reconnected (EmpathyDispatchOperation *dispatch,
225                                   const GError             *error,
226                                   gpointer                  user_data)
227 {
228         EmpathyChat *chat = EMPATHY_CHAT (user_data);
229         EmpathyTpChat *tpchat;
230
231         if (error != NULL) {
232                 empathy_chat_view_append_event (chat->view,
233                         _("Failed to reconnect this chat"));
234                 return;
235         }
236
237         tpchat = EMPATHY_TP_CHAT (
238                 empathy_dispatch_operation_get_channel_wrapper (dispatch));
239
240         if (empathy_dispatch_operation_claim (dispatch)) {
241                 empathy_chat_set_tp_chat (chat, tpchat);
242         }
243 }
244
245 static void
246 reconnected_connection_ready_cb (TpConnection *connection,
247                         const GError *error,
248                         gpointer user_data)
249 {
250         EmpathyChat *chat = user_data;
251         EmpathyChatPriv *priv = GET_PRIV (chat);
252
253         if (error != NULL) {
254                 DEBUG ("connection is not ready: %s", error->message);
255                 goto out;
256         }
257
258         DEBUG ("Account reconnected, request a new Text channel");
259
260         switch (priv->handle_type) {
261                 case TP_HANDLE_TYPE_CONTACT:
262                         empathy_dispatcher_chat_with_contact_id (
263                                 connection, priv->id,
264                                 chat_connect_channel_reconnected,
265                                 chat);
266                         break;
267                 case TP_HANDLE_TYPE_ROOM:
268                         empathy_dispatcher_join_muc (connection,
269                                 priv->id,
270                                 chat_connect_channel_reconnected,
271                                 chat);
272                         break;
273                 default:
274                         g_assert_not_reached ();
275                         break;
276         }
277
278 out:
279         g_object_unref (chat);
280 }
281
282 static void
283 chat_new_connection_cb (TpAccount   *account,
284                         guint        old_status,
285                         guint        new_status,
286                         guint        reason,
287                         gchar       *dbus_error_name,
288                         GHashTable  *details,
289                         EmpathyChat *chat)
290 {
291         EmpathyChatPriv *priv = GET_PRIV (chat);
292         TpConnection *connection;
293
294         if (new_status != TP_CONNECTION_STATUS_CONNECTED)
295                 return;
296
297         connection = tp_account_get_connection (account);
298
299         if (priv->tp_chat != NULL || account != priv->account ||
300             priv->handle_type == TP_HANDLE_TYPE_NONE ||
301             EMP_STR_EMPTY (priv->id))
302                 return;
303
304         g_object_ref (chat);
305         tp_connection_call_when_ready (connection, reconnected_connection_ready_cb,
306                                    chat);
307 }
308
309 static void
310 chat_composing_remove_timeout (EmpathyChat *chat)
311 {
312         EmpathyChatPriv *priv;
313
314         priv = GET_PRIV (chat);
315
316         if (priv->composing_stop_timeout_id) {
317                 g_source_remove (priv->composing_stop_timeout_id);
318                 priv->composing_stop_timeout_id = 0;
319         }
320 }
321
322 static gboolean
323 chat_composing_stop_timeout_cb (EmpathyChat *chat)
324 {
325         EmpathyChatPriv *priv;
326
327         priv = GET_PRIV (chat);
328
329         priv->composing_stop_timeout_id = 0;
330         empathy_tp_chat_set_state (priv->tp_chat,
331                                    TP_CHANNEL_CHAT_STATE_PAUSED);
332
333         return FALSE;
334 }
335
336 static void
337 chat_composing_start (EmpathyChat *chat)
338 {
339         EmpathyChatPriv *priv;
340
341         priv = GET_PRIV (chat);
342
343         if (priv->composing_stop_timeout_id) {
344                 /* Just restart the timeout */
345                 chat_composing_remove_timeout (chat);
346         } else {
347                 empathy_tp_chat_set_state (priv->tp_chat,
348                                            TP_CHANNEL_CHAT_STATE_COMPOSING);
349         }
350
351         priv->composing_stop_timeout_id = g_timeout_add_seconds (
352                 COMPOSING_STOP_TIMEOUT,
353                 (GSourceFunc) chat_composing_stop_timeout_cb,
354                 chat);
355 }
356
357 static void
358 chat_composing_stop (EmpathyChat *chat)
359 {
360         EmpathyChatPriv *priv;
361
362         priv = GET_PRIV (chat);
363
364         chat_composing_remove_timeout (chat);
365         empathy_tp_chat_set_state (priv->tp_chat,
366                                    TP_CHANNEL_CHAT_STATE_ACTIVE);
367 }
368
369 static gint
370 chat_input_history_entry_cmp (InputHistoryEntry *entry,
371                               const gchar *text)
372 {
373         if (!tp_strdiff (entry->text, text)) {
374                 if (entry->modified_text != NULL) {
375                         /* Modified entry and single string cannot be equal. */
376                         return 1;
377                 }
378                 return 0;
379         }
380         return 1;
381 }
382
383 static InputHistoryEntry *
384 chat_input_history_entry_new_with_text (const gchar *text)
385 {
386         InputHistoryEntry *entry;
387         entry = g_slice_new0 (InputHistoryEntry);
388         entry->text = g_strdup (text);
389
390         return entry;
391 }
392
393 static void
394 chat_input_history_entry_free (InputHistoryEntry *entry)
395 {
396         g_free (entry->text);
397         g_free (entry->modified_text);
398         g_slice_free (InputHistoryEntry, entry);
399 }
400
401 static void
402 chat_input_history_entry_revert (InputHistoryEntry *entry)
403 {
404         g_free (entry->modified_text);
405         entry->modified_text = NULL;
406 }
407
408 static void
409 chat_input_history_entry_update_text (InputHistoryEntry *entry,
410                                       const gchar *text)
411 {
412         gchar *old;
413
414         if (!tp_strdiff (text, entry->text)) {
415                 g_free (entry->modified_text);
416                 entry->modified_text = NULL;
417                 return;
418         }
419
420         old = entry->modified_text;
421         entry->modified_text = g_strdup (text);
422         g_free (old);
423 }
424
425 static const gchar *
426 chat_input_history_entry_get_text (InputHistoryEntry *entry)
427 {
428         if (entry == NULL) {
429                 return NULL;
430         }
431
432         if (entry->modified_text != NULL) {
433                 return entry->modified_text;
434         }
435         return entry->text;
436 }
437
438 static GList *
439 chat_input_history_remove_item (GList *list,
440                                 GList *item)
441 {
442         list = g_list_remove_link (list, item);
443         chat_input_history_entry_free (item->data);
444         g_list_free_1 (item);
445         return list;
446 }
447
448 static void
449 chat_input_history_revert (EmpathyChat *chat)
450 {
451         EmpathyChatPriv   *priv;
452         GList             *list;
453         GList             *item1;
454         GList             *item2;
455         InputHistoryEntry *entry;
456
457         priv = GET_PRIV (chat);
458         list = priv->input_history;
459
460         if (list == NULL) {
461                 DEBUG ("No input history");
462                 return;
463         }
464
465         /* Delete temporary entry */
466         if (priv->input_history_current != NULL) {
467                 item1 = list;
468                 list = chat_input_history_remove_item (list, item1);
469                 if (priv->input_history_current == item1) {
470                         /* Removed temporary entry was current entry */
471                         priv->input_history = list;
472                         priv->input_history_current = NULL;
473                         return;
474                 }
475         }
476         else {
477                 /* There is no entry to revert */
478                 return;
479         }
480
481         /* Restore the current history entry to original value */
482         item1 = priv->input_history_current;
483         entry = item1->data;
484         chat_input_history_entry_revert (entry);
485
486         /* Remove restored entry if there is other occurance before this entry */
487         item2 = g_list_find_custom (list, chat_input_history_entry_get_text (entry),
488                                     (GCompareFunc) chat_input_history_entry_cmp);
489         if (item2 != item1) {
490                 list = chat_input_history_remove_item (list, item1);
491         }
492         else {
493                 /* Remove other occurance of the restored entry */
494                 item2 = g_list_find_custom (item1->next,
495                                             chat_input_history_entry_get_text (entry),
496                                             (GCompareFunc) chat_input_history_entry_cmp);
497                 if (item2 != NULL) {
498                         list = chat_input_history_remove_item (list, item2);
499                 }
500         }
501
502         priv->input_history_current = NULL;
503         priv->input_history = list;
504 }
505
506 static void
507 chat_input_history_add (EmpathyChat  *chat,
508                         const gchar *str,
509                         gboolean temporary)
510 {
511         EmpathyChatPriv   *priv;
512         GList             *list;
513         GList             *item;
514         InputHistoryEntry *entry;
515
516         priv = GET_PRIV (chat);
517
518         list = priv->input_history;
519
520         /* Remove any other occurances of this entry, if not temporary */
521         if (!temporary) {
522                 while ((item = g_list_find_custom (list, str,
523                     (GCompareFunc) chat_input_history_entry_cmp)) != NULL) {
524                         list = chat_input_history_remove_item (list, item);
525                 }
526
527                 /* Trim the list to the last 10 items */
528                 while (g_list_length (list) > 10) {
529                         item = g_list_last (list);
530                         if (item != NULL) {
531                                 list = chat_input_history_remove_item (list, item);
532                         }
533                 }
534         }
535
536
537
538         /* Add new entry */
539         entry = chat_input_history_entry_new_with_text (str);
540         list = g_list_prepend (list, entry);
541
542         /* Set the list and the current item pointer */
543         priv->input_history = list;
544         if (temporary) {
545                 priv->input_history_current = list;
546         }
547         else {
548                 priv->input_history_current = NULL;
549         }
550 }
551
552 static const gchar *
553 chat_input_history_get_next (EmpathyChat *chat)
554 {
555         EmpathyChatPriv *priv;
556         GList           *item;
557         const gchar     *msg;
558
559         priv = GET_PRIV (chat);
560
561         if (priv->input_history == NULL) {
562                 DEBUG ("No input history, next entry is NULL");
563                 return NULL;
564         }
565         g_assert (priv->input_history_current != NULL);
566
567         if ((item = g_list_next (priv->input_history_current)) == NULL)
568         {
569                 item = priv->input_history_current;
570         }
571
572         msg = chat_input_history_entry_get_text (item->data);
573
574         DEBUG ("Returning next entry: '%s'", msg);
575
576         priv->input_history_current = item;
577
578         return msg;
579 }
580
581 static const gchar *
582 chat_input_history_get_prev (EmpathyChat *chat)
583 {
584         EmpathyChatPriv *priv;
585         GList           *item;
586         const gchar     *msg;
587
588         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
589
590         priv = GET_PRIV (chat);
591
592         if (priv->input_history == NULL) {
593                 DEBUG ("No input history, previous entry is NULL");
594                 return NULL;
595         }
596
597         if (priv->input_history_current == NULL)
598         {
599                 return NULL;
600         }
601         else if ((item = g_list_previous (priv->input_history_current)) == NULL)
602         {
603                 item = priv->input_history_current;
604         }
605
606         msg = chat_input_history_entry_get_text (item->data);
607
608         DEBUG ("Returning previous entry: '%s'", msg);
609
610         priv->input_history_current = item;
611
612         return msg;
613 }
614
615 static void
616 chat_input_history_update (EmpathyChat *chat,
617                            GtkTextBuffer *buffer)
618 {
619         EmpathyChatPriv      *priv;
620         GtkTextIter           start, end;
621         gchar                *text;
622         InputHistoryEntry    *entry;
623
624         priv = GET_PRIV (chat);
625
626         gtk_text_buffer_get_bounds (buffer, &start, &end);
627         text = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
628
629         if (priv->input_history_current == NULL) {
630                 /* Add the current text temporarily to the history */
631                 chat_input_history_add (chat, text, TRUE);
632                 g_free (text);
633                 return;
634         }
635
636         /* Save the changes in the history */
637         entry = priv->input_history_current->data;
638         if (tp_strdiff (chat_input_history_entry_get_text (entry), text)) {
639                 chat_input_history_entry_update_text (entry, text);
640         }
641
642         g_free (text);
643 }
644
645 static void
646 chat_command_join_cb (EmpathyDispatchOperation *dispatch,
647                       const GError             *error,
648                       gpointer                  user_data)
649 {
650         EmpathyChat *chat = user_data;
651
652         if (error != NULL) {
653                 DEBUG ("Error: %s", error->message);
654                 empathy_chat_view_append_event (chat->view,
655                         _("Failed to join chat room"));
656         }
657 }
658
659 typedef struct {
660         EmpathyChat *chat;
661         gchar *message;
662 } ChatCommandMsgData;
663
664 static void
665 chat_command_msg_cb (EmpathyDispatchOperation *dispatch,
666                               const GError             *error,
667                               gpointer                  user_data)
668 {
669         ChatCommandMsgData *data = user_data;
670
671         if (error != NULL) {
672                 empathy_chat_view_append_event (data->chat->view,
673                         _("Failed to open private chat"));
674                 goto OUT;
675         }
676
677         if (!EMP_STR_EMPTY (data->message)) {
678                 EmpathyTpChat *tpchat;
679                 EmpathyMessage *message;
680
681                 tpchat = EMPATHY_TP_CHAT (
682                         empathy_dispatch_operation_get_channel_wrapper (dispatch));
683
684                 message = empathy_message_new (data->message);
685                 empathy_tp_chat_send (tpchat, message);
686                 g_object_unref (message);
687         }
688
689 OUT:
690         g_free (data->message);
691         g_slice_free (ChatCommandMsgData, data);
692 }
693
694 static void
695 chat_command_clear (EmpathyChat *chat,
696                     GStrv        strv)
697 {
698         empathy_chat_view_clear (chat->view);
699 }
700
701 static void
702 chat_command_topic (EmpathyChat *chat,
703                     GStrv        strv)
704 {
705         EmpathyChatPriv *priv = GET_PRIV (chat);
706         EmpathyTpChatProperty *property;
707         GValue value = {0, };
708
709         property = empathy_tp_chat_get_property (priv->tp_chat, "subject");
710         if (property == NULL) {
711                 empathy_chat_view_append_event (chat->view,
712                         _("Topic not supported on this conversation"));
713                 return;
714         }
715
716         if (!(property->flags & TP_PROPERTY_FLAG_WRITE)) {
717                 empathy_chat_view_append_event (chat->view,
718                         _("You are not allowed to change the topic"));
719                 return;
720         }
721
722         g_value_init (&value, G_TYPE_STRING);
723         g_value_set_string (&value, strv[1]);
724         empathy_tp_chat_set_property (priv->tp_chat, "subject", &value);
725         g_value_unset (&value);
726 }
727
728 static void
729 chat_command_join (EmpathyChat *chat,
730                    GStrv        strv)
731 {
732         guint i = 0;
733         EmpathyChatPriv *priv = GET_PRIV (chat);
734
735         GStrv rooms = g_strsplit_set (strv[1], ", ", -1);
736
737         while (rooms[i] != NULL) {
738                 /* ignore empty strings */
739                 if (!EMP_STR_EMPTY (rooms[i])) {
740                         TpConnection *connection;
741
742                         connection = empathy_tp_chat_get_connection (priv->tp_chat);
743                         empathy_dispatcher_join_muc (connection, rooms[i],
744                                                      chat_command_join_cb,
745                                                      chat);
746                 }
747                 i++;
748         }
749         g_strfreev (rooms);
750 }
751
752 static void
753 chat_command_msg_internal (EmpathyChat *chat,
754                            const gchar *contact_id,
755                            const gchar *message)
756 {
757         EmpathyChatPriv *priv = GET_PRIV (chat);
758         TpConnection *connection;
759         ChatCommandMsgData *data;
760
761         /* FIXME: We should probably search in members alias. But this
762          * is enough for IRC */
763         data = g_slice_new (ChatCommandMsgData);
764         data->chat = chat;
765         data->message = g_strdup (message);
766         connection = empathy_tp_chat_get_connection (priv->tp_chat);
767         empathy_dispatcher_chat_with_contact_id (connection, contact_id,
768                                                  chat_command_msg_cb,
769                                                  data);
770 }
771
772 static void
773 chat_command_query (EmpathyChat *chat,
774                     GStrv        strv)
775 {
776         /* If <message> part is not defined,
777          * strv[2] will be the terminal NULL */
778         chat_command_msg_internal (chat, strv[1], strv[2]);
779 }
780
781 static void
782 chat_command_msg (EmpathyChat *chat,
783                   GStrv        strv)
784 {
785         chat_command_msg_internal (chat, strv[1], strv[2]);
786 }
787
788 static void
789 chat_command_nick (EmpathyChat *chat,
790                    GStrv        strv)
791 {
792         EmpathyChatPriv *priv = GET_PRIV (chat);
793         TpConnection *connection;
794         GHashTable *new_alias;
795         TpHandle handle;
796
797         connection = tp_account_get_connection (priv->account);
798         handle = tp_connection_get_self_handle (connection);
799         new_alias = g_hash_table_new (g_direct_hash, g_direct_equal);
800         g_hash_table_insert (new_alias, GUINT_TO_POINTER (handle), strv[1]);
801
802         tp_cli_connection_interface_aliasing_call_set_aliases (connection, -1,
803                 new_alias, NULL, NULL, NULL, NULL);
804
805         g_hash_table_destroy (new_alias);
806 }
807
808 static void
809 chat_command_me (EmpathyChat *chat,
810                   GStrv        strv)
811 {
812         EmpathyChatPriv *priv = GET_PRIV (chat);
813         EmpathyMessage *message;
814
815         message = empathy_message_new (strv[1]);
816         empathy_message_set_tptype (message, TP_CHANNEL_TEXT_MESSAGE_TYPE_ACTION);
817         empathy_tp_chat_send (priv->tp_chat, message);
818         g_object_unref (message);
819 }
820
821 static void
822 chat_command_say (EmpathyChat *chat,
823                   GStrv        strv)
824 {
825         EmpathyChatPriv *priv = GET_PRIV (chat);
826         EmpathyMessage *message;
827
828         message = empathy_message_new (strv[1]);
829         empathy_tp_chat_send (priv->tp_chat, message);
830         g_object_unref (message);
831 }
832
833 static void chat_command_help (EmpathyChat *chat, GStrv strv);
834
835 typedef void (*ChatCommandFunc) (EmpathyChat *chat, GStrv strv);
836
837 typedef struct {
838         const gchar *prefix;
839         guint min_parts;
840         guint max_parts;
841         ChatCommandFunc func;
842         const gchar *help;
843 } ChatCommandItem;
844
845 static ChatCommandItem commands[] = {
846         {"clear", 1, 1, chat_command_clear,
847          N_("/clear: clear all messages from the current conversation")},
848
849         {"topic", 2, 2, chat_command_topic,
850          N_("/topic <topic>: set the topic of the current conversation")},
851
852         {"join", 2, 2, chat_command_join,
853          N_("/join <chat room ID>: join a new chat room")},
854
855         {"j", 2, 2, chat_command_join,
856          N_("/j <chat room ID>: join a new chat room")},
857
858         {"query", 2, 3, chat_command_query,
859          N_("/query <contact ID> [<message>]: open a private chat")},
860
861         {"msg", 3, 3, chat_command_msg,
862          N_("/msg <contact ID> <message>: open a private chat")},
863
864         {"nick", 2, 2, chat_command_nick,
865          N_("/nick <nickname>: change your nickname on the current server")},
866
867         {"me", 2, 2, chat_command_me,
868          N_("/me <message>: send an ACTION message to the current conversation")},
869
870         {"say", 2, 2, chat_command_say,
871          N_("/say <message>: send <message> to the current conversation. "
872             "This is used to send a message starting with a '/'. For example: "
873             "\"/say /join is used to join a new chat room\"")},
874
875         {"help", 1, 2, chat_command_help,
876          N_("/help [<command>]: show all supported commands. "
877             "If <command> is defined, show its usage.")},
878 };
879
880 static void
881 chat_command_show_help (EmpathyChat     *chat,
882                         ChatCommandItem *item)
883 {
884         gchar *str;
885
886         str = g_strdup_printf (_("Usage: %s"), _(item->help));
887         empathy_chat_view_append_event (chat->view, str);
888         g_free (str);
889 }
890
891 static void
892 chat_command_help (EmpathyChat *chat,
893                    GStrv        strv)
894 {
895         guint i;
896
897         /* If <command> part is not defined,
898          * strv[1] will be the terminal NULL */
899         if (strv[1] == NULL) {
900                 for (i = 0; i < G_N_ELEMENTS (commands); i++) {
901                         empathy_chat_view_append_event (chat->view,
902                                 _(commands[i].help));
903                 }
904                 return;
905         }
906
907         for (i = 0; i < G_N_ELEMENTS (commands); i++) {
908                 if (g_ascii_strcasecmp (strv[1], commands[i].prefix) == 0) {
909                         chat_command_show_help (chat, &commands[i]);
910                         return;
911                 }
912         }
913
914         empathy_chat_view_append_event (chat->view,
915                 _("Unknown command"));
916 }
917
918 static GStrv
919 chat_command_parse (const gchar *text, guint max_parts)
920 {
921         GPtrArray *array;
922         gchar *item;
923
924         DEBUG ("Parse command, parts=%d text=\"%s\":", max_parts, text);
925
926         array = g_ptr_array_sized_new (max_parts + 1);
927         while (max_parts > 1) {
928                 const gchar *end;
929
930                 /* Skip white spaces */
931                 while (g_ascii_isspace (*text)) {
932                         text++;
933                 }
934
935                 /* Search the end of this part, until first space. */
936                 for (end = text; *end != '\0' && !g_ascii_isspace (*end); end++)
937                         /* Do nothing */;
938                 if (*end == '\0') {
939                         break;
940                 }
941
942                 item = g_strndup (text, end - text);
943                 g_ptr_array_add (array, item);
944                 DEBUG ("\tITEM: \"%s\"", item);
945
946                 text = end;
947                 max_parts--;
948         }
949
950         /* Append last part if not empty */
951         item = g_strstrip (g_strdup (text));
952         if (!EMP_STR_EMPTY (item)) {
953                 g_ptr_array_add (array, item);
954                 DEBUG ("\tITEM: \"%s\"", item);
955         } else {
956                 g_free (item);
957         }
958
959         /* Make the array NULL-terminated */
960         g_ptr_array_add (array, NULL);
961
962         return (GStrv) g_ptr_array_free (array, FALSE);
963 }
964
965 static gboolean
966 has_prefix_case (const gchar *s,
967                   const gchar *prefix)
968 {
969         return g_ascii_strncasecmp (s, prefix, strlen (prefix)) == 0;
970 }
971
972 static void
973 chat_send (EmpathyChat  *chat,
974            const gchar *msg)
975 {
976         EmpathyChatPriv *priv;
977         EmpathyMessage  *message;
978         guint            i;
979
980         if (EMP_STR_EMPTY (msg)) {
981                 return;
982         }
983
984         priv = GET_PRIV (chat);
985
986         chat_input_history_add (chat, msg, FALSE);
987
988         if (msg[0] == '/') {
989                 gboolean second_slash = FALSE;
990                 const gchar *iter = msg + 1;
991
992                 for (i = 0; i < G_N_ELEMENTS (commands); i++) {
993                         GStrv strv;
994                         guint strv_len;
995                         gchar c;
996
997                         if (!has_prefix_case (msg + 1, commands[i].prefix)) {
998                                 continue;
999                         }
1000                         c = *(msg + 1 + strlen (commands[i].prefix));
1001                         if (c != '\0' && !g_ascii_isspace (c)) {
1002                                 continue;
1003                         }
1004
1005                         /* We can't use g_strsplit here because it does
1006                          * not deal correctly if we have more than one space
1007                          * between args */
1008                         strv = chat_command_parse (msg + 1, commands[i].max_parts);
1009
1010                         strv_len = g_strv_length (strv);
1011                         if (strv_len < commands[i].min_parts ||
1012                             strv_len > commands[i].max_parts) {
1013                                 chat_command_show_help (chat, &commands[i]);
1014                                 g_strfreev (strv);
1015                                 return;
1016                         }
1017
1018                         commands[i].func (chat, strv);
1019                         g_strfreev (strv);
1020                         return;
1021                 }
1022
1023                 /* Also allow messages with two slashes before the
1024                  * first space, so it is possible to send a /unix/path.
1025                  * This heuristic is kind of crap. */
1026                 while (*iter != '\0' && !g_ascii_isspace (*iter)) {
1027                         if (*iter == '/') {
1028                                 second_slash = TRUE;
1029                                 break;
1030                         }
1031                         iter++;
1032                 }
1033
1034                 if (!second_slash) {
1035                         empathy_chat_view_append_event (chat->view,
1036                                 _("Unknown command; see /help for the available"
1037                                   " commands"));
1038                         return;
1039                 }
1040         }
1041
1042         message = empathy_message_new (msg);
1043         empathy_tp_chat_send (priv->tp_chat, message);
1044         g_object_unref (message);
1045 }
1046
1047 static void
1048 chat_input_text_view_send (EmpathyChat *chat)
1049 {
1050         EmpathyChatPriv *priv;
1051         GtkTextBuffer  *buffer;
1052         GtkTextIter     start, end;
1053         gchar          *msg;
1054
1055         priv = GET_PRIV (chat);
1056
1057         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1058
1059         gtk_text_buffer_get_bounds (buffer, &start, &end);
1060         msg = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1061
1062         /* clear the input field */
1063         gtk_text_buffer_set_text (buffer, "", -1);
1064         /* delete input history modifications */
1065         chat_input_history_revert (chat);
1066
1067         chat_send (chat, msg);
1068         g_free (msg);
1069 }
1070
1071 static void
1072 chat_state_changed_cb (EmpathyTpChat      *tp_chat,
1073                        EmpathyContact     *contact,
1074                        TpChannelChatState  state,
1075                        EmpathyChat        *chat)
1076 {
1077         EmpathyChatPriv *priv;
1078         GList          *l;
1079         gboolean        was_composing;
1080
1081         priv = GET_PRIV (chat);
1082
1083         if (empathy_contact_is_user (contact)) {
1084                 /* We don't care about our own chat state */
1085                 return;
1086         }
1087
1088         was_composing = (priv->compositors != NULL);
1089
1090         /* Find the contact in the list. After that l is the list elem or NULL */
1091         for (l = priv->compositors; l; l = l->next) {
1092                 if (contact == l->data) {
1093                         break;
1094                 }
1095         }
1096
1097         switch (state) {
1098         case TP_CHANNEL_CHAT_STATE_GONE:
1099         case TP_CHANNEL_CHAT_STATE_INACTIVE:
1100         case TP_CHANNEL_CHAT_STATE_PAUSED:
1101         case TP_CHANNEL_CHAT_STATE_ACTIVE:
1102                 /* Contact is not composing */
1103                 if (l) {
1104                         priv->compositors = g_list_remove_link (priv->compositors, l);
1105                         g_object_unref (l->data);
1106                         g_list_free1 (l);
1107                 }
1108                 break;
1109         case TP_CHANNEL_CHAT_STATE_COMPOSING:
1110                 /* Contact is composing */
1111                 if (!l) {
1112                         priv->compositors = g_list_prepend (priv->compositors,
1113                                                             g_object_ref (contact));
1114                 }
1115                 break;
1116         default:
1117                 g_assert_not_reached ();
1118         }
1119
1120         DEBUG ("Was composing: %s now composing: %s",
1121                 was_composing ? "yes" : "no",
1122                 priv->compositors ? "yes" : "no");
1123
1124         if ((was_composing && !priv->compositors) ||
1125             (!was_composing && priv->compositors)) {
1126                 /* Composing state changed */
1127                 g_signal_emit (chat, signals[COMPOSING], 0,
1128                                priv->compositors != NULL);
1129         }
1130 }
1131
1132 static void
1133 chat_message_received (EmpathyChat *chat, EmpathyMessage *message)
1134 {
1135         EmpathyChatPriv *priv = GET_PRIV (chat);
1136         EmpathyContact  *sender;
1137
1138         sender = empathy_message_get_sender (message);
1139
1140         DEBUG ("Appending new message from %s (%d)",
1141                 empathy_contact_get_name (sender),
1142                 empathy_contact_get_handle (sender));
1143
1144         empathy_chat_view_append_message (chat->view, message);
1145
1146         /* We received a message so the contact is no longer composing */
1147         chat_state_changed_cb (priv->tp_chat, sender,
1148                                TP_CHANNEL_CHAT_STATE_ACTIVE,
1149                                chat);
1150
1151         priv->unread_messages++;
1152         g_signal_emit (chat, signals[NEW_MESSAGE], 0, message);
1153 }
1154
1155 static void
1156 chat_message_received_cb (EmpathyTpChat  *tp_chat,
1157                           EmpathyMessage *message,
1158                           EmpathyChat    *chat)
1159 {
1160         chat_message_received (chat, message);
1161 }
1162
1163 static void
1164 chat_send_error_cb (EmpathyTpChat          *tp_chat,
1165                     const gchar            *message_body,
1166                     TpChannelTextSendError  error_code,
1167                     EmpathyChat            *chat)
1168 {
1169         const gchar *error;
1170         gchar       *str;
1171
1172         switch (error_code) {
1173         case TP_CHANNEL_TEXT_SEND_ERROR_OFFLINE:
1174                 error = _("offline");
1175                 break;
1176         case TP_CHANNEL_TEXT_SEND_ERROR_INVALID_CONTACT:
1177                 error = _("invalid contact");
1178                 break;
1179         case TP_CHANNEL_TEXT_SEND_ERROR_PERMISSION_DENIED:
1180                 error = _("permission denied");
1181                 break;
1182         case TP_CHANNEL_TEXT_SEND_ERROR_TOO_LONG:
1183                 error = _("too long message");
1184                 break;
1185         case TP_CHANNEL_TEXT_SEND_ERROR_NOT_IMPLEMENTED:
1186                 error = _("not implemented");
1187                 break;
1188         default:
1189                 error = _("unknown");
1190                 break;
1191         }
1192
1193         str = g_strdup_printf (_("Error sending message '%s': %s"),
1194                                message_body,
1195                                error);
1196         empathy_chat_view_append_event (chat->view, str);
1197         g_free (str);
1198 }
1199
1200 static void
1201 chat_property_changed_cb (EmpathyTpChat *tp_chat,
1202                           const gchar   *name,
1203                           GValue        *value,
1204                           EmpathyChat   *chat)
1205 {
1206         EmpathyChatPriv *priv = GET_PRIV (chat);
1207
1208         if (!tp_strdiff (name, "subject")) {
1209                 g_free (priv->subject);
1210                 priv->subject = g_value_dup_string (value);
1211                 g_object_notify (G_OBJECT (chat), "subject");
1212
1213                 if (EMP_STR_EMPTY (priv->subject)) {
1214                         gtk_widget_hide (priv->hbox_topic);
1215                 } else {
1216                         gchar *markup_text;
1217
1218                         markup_text = empathy_add_link_markup (priv->subject);
1219                         gtk_label_set_markup (GTK_LABEL (priv->label_topic), markup_text);
1220                         g_free (markup_text);
1221
1222                         gtk_widget_show (priv->hbox_topic);
1223                 }
1224                 if (priv->block_events_timeout_id == 0) {
1225                         gchar *str;
1226
1227                         if (!EMP_STR_EMPTY (priv->subject)) {
1228                                 str = g_strdup_printf (_("Topic set to: %s"), priv->subject);
1229                         } else {
1230                                 str = g_strdup (_("No topic defined"));
1231                         }
1232                         empathy_chat_view_append_event (EMPATHY_CHAT (chat)->view, str);
1233                         g_free (str);
1234                 }
1235         }
1236         else if (!tp_strdiff (name, "name")) {
1237                 g_free (priv->name);
1238                 priv->name = g_value_dup_string (value);
1239                 g_object_notify (G_OBJECT (chat), "name");
1240         }
1241 }
1242
1243 static void
1244 chat_input_text_buffer_changed_cb (GtkTextBuffer *buffer,
1245                                    EmpathyChat    *chat)
1246 {
1247         GtkTextIter     start, end;
1248         gchar          *str;
1249         gboolean        spell_checker = FALSE;
1250
1251         if (gtk_text_buffer_get_char_count (buffer) == 0) {
1252                 chat_composing_stop (chat);
1253         } else {
1254                 chat_composing_start (chat);
1255         }
1256
1257         empathy_conf_get_bool (empathy_conf_get (),
1258                            EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED,
1259                            &spell_checker);
1260
1261         gtk_text_buffer_get_start_iter (buffer, &start);
1262
1263         if (!spell_checker) {
1264                 gtk_text_buffer_get_end_iter (buffer, &end);
1265                 gtk_text_buffer_remove_tag_by_name (buffer, "misspelled", &start, &end);
1266                 return;
1267         }
1268
1269         if (!empathy_spell_supported ()) {
1270                 return;
1271         }
1272
1273         /* NOTE: this is really inefficient, we shouldn't have to
1274            reiterate the whole buffer each time and check each work
1275            every time. */
1276         while (TRUE) {
1277                 gboolean correct = FALSE;
1278
1279                 /* if at start */
1280                 if (gtk_text_iter_is_start (&start)) {
1281                         end = start;
1282
1283                         if (!gtk_text_iter_forward_word_end (&end)) {
1284                                 /* no whole word yet */
1285                                 break;
1286                         }
1287                 } else {
1288                         if (!gtk_text_iter_forward_word_end (&end)) {
1289                                 /* must be the end of the buffer */
1290                                 break;
1291                         }
1292
1293                         start = end;
1294                         gtk_text_iter_backward_word_start (&start);
1295                 }
1296
1297                 str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1298
1299                 /* spell check string if not a command */
1300                 if (str[0] != '/') {
1301                         correct = empathy_spell_check (str);
1302                 } else {
1303                         correct = TRUE;
1304                 }
1305
1306                 if (!correct) {
1307                         gtk_text_buffer_apply_tag_by_name (buffer, "misspelled", &start, &end);
1308                 } else {
1309                         gtk_text_buffer_remove_tag_by_name (buffer, "misspelled", &start, &end);
1310                 }
1311
1312                 g_free (str);
1313
1314                 /* set start iter to the end iters position */
1315                 start = end;
1316         }
1317 }
1318
1319 static gboolean
1320 empathy_isspace_cb (gunichar c,
1321                  gpointer data)
1322 {
1323         return g_unichar_isspace (c);
1324 }
1325
1326 static gboolean
1327 chat_input_key_press_event_cb (GtkWidget   *widget,
1328                                GdkEventKey *event,
1329                                EmpathyChat *chat)
1330 {
1331         EmpathyChatPriv *priv;
1332         GtkAdjustment  *adj;
1333         gdouble         val;
1334         GtkWidget      *text_view_sw;
1335
1336         priv = GET_PRIV (chat);
1337
1338         /* Catch ctrl+up/down so we can traverse messages we sent */
1339         if ((event->state & GDK_CONTROL_MASK) &&
1340             (event->keyval == GDK_Up ||
1341              event->keyval == GDK_Down)) {
1342                 GtkTextBuffer *buffer;
1343                 const gchar   *str;
1344
1345                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1346                 chat_input_history_update (chat, buffer);
1347
1348                 if (event->keyval == GDK_Up) {
1349                         str = chat_input_history_get_next (chat);
1350                 } else {
1351                         str = chat_input_history_get_prev (chat);
1352                 }
1353
1354                 g_signal_handlers_block_by_func (buffer,
1355                                                  chat_input_text_buffer_changed_cb,
1356                                                  chat);
1357                 gtk_text_buffer_set_text (buffer, str ? str : "", -1);
1358                 g_signal_handlers_unblock_by_func (buffer,
1359                                                    chat_input_text_buffer_changed_cb,
1360                                                    chat);
1361
1362                 return TRUE;
1363         }
1364
1365         /* Catch enter but not ctrl/shift-enter */
1366         if (IS_ENTER (event->keyval) &&
1367             !(event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
1368                 GtkTextView *view;
1369
1370                 /* This is to make sure that kinput2 gets the enter. And if
1371                  * it's handled there we shouldn't send on it. This is because
1372                  * kinput2 uses Enter to commit letters. See:
1373                  * http://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=104299
1374                  */
1375
1376                 view = GTK_TEXT_VIEW (chat->input_text_view);
1377                 if (gtk_im_context_filter_keypress (view->im_context, event)) {
1378                         GTK_TEXT_VIEW (chat->input_text_view)->need_im_reset = TRUE;
1379                         return TRUE;
1380                 }
1381
1382                 chat_input_text_view_send (chat);
1383                 return TRUE;
1384         }
1385
1386         text_view_sw = gtk_widget_get_parent (GTK_WIDGET (chat->view));
1387
1388         if (IS_ENTER (event->keyval) &&
1389             (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
1390                 /* Newline for shift/control-enter. */
1391                 return FALSE;
1392         }
1393         if (!(event->state & GDK_CONTROL_MASK) &&
1394             event->keyval == GDK_Page_Up) {
1395                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
1396                 gtk_adjustment_set_value (adj, gtk_adjustment_get_value (adj) - gtk_adjustment_get_page_size (adj));
1397                 return TRUE;
1398         }
1399         if ((event->state & GDK_CONTROL_MASK) != GDK_CONTROL_MASK &&
1400             event->keyval == GDK_Page_Down) {
1401                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
1402                 val = MIN (gtk_adjustment_get_value (adj) + gtk_adjustment_get_page_size (adj),
1403                            gtk_adjustment_get_upper (adj) - gtk_adjustment_get_page_size (adj));
1404                 gtk_adjustment_set_value (adj, val);
1405                 return TRUE;
1406         }
1407         if (event->keyval == GDK_Escape) {
1408                 empathy_search_bar_hide (EMPATHY_SEARCH_BAR (priv->search_bar));
1409         }
1410         if (!(event->state & (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) &&
1411             event->keyval == GDK_Tab) {
1412                 GtkTextBuffer *buffer;
1413                 GtkTextIter    start, current;
1414                 gchar         *nick, *completed;
1415                 GList         *list, *completed_list;
1416                 gboolean       is_start_of_buffer;
1417
1418                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (EMPATHY_CHAT (chat)->input_text_view));
1419                 gtk_text_buffer_get_iter_at_mark (buffer, &current, gtk_text_buffer_get_insert (buffer));
1420
1421                 /* Get the start of the nick to complete. */
1422                 gtk_text_buffer_get_iter_at_mark (buffer, &start, gtk_text_buffer_get_insert (buffer));
1423                 if (gtk_text_iter_backward_find_char (&start, &empathy_isspace_cb, NULL, NULL)) {
1424                         gtk_text_iter_set_offset (&start, gtk_text_iter_get_offset (&start) + 1);
1425                 }
1426                 is_start_of_buffer = gtk_text_iter_is_start (&start);
1427
1428                 list = empathy_contact_list_get_members (EMPATHY_CONTACT_LIST (priv->tp_chat));
1429                 g_completion_add_items (priv->completion, list);
1430
1431                 nick = gtk_text_buffer_get_text (buffer, &start, &current, FALSE);
1432                 completed_list = g_completion_complete (priv->completion,
1433                                                         nick,
1434                                                         &completed);
1435
1436                 g_free (nick);
1437
1438                 if (completed) {
1439                         guint        len;
1440                         const gchar *text;
1441                         gchar       *complete_char = NULL;
1442                         GString     *message = NULL;
1443                         GList       *l;
1444
1445                         gtk_text_buffer_delete (buffer, &start, &current);
1446
1447                         len = g_list_length (completed_list);
1448
1449                         if (len == 1) {
1450                                 /* If we only have one hit, use that text
1451                                  * instead of the text in completed since the
1452                                  * completed text will use the typed string
1453                                  * which might be cased all wrong.
1454                                  * Fixes #120876
1455                                  * */
1456                                 text = empathy_contact_get_name (completed_list->data);
1457                         } else {
1458                                 text = completed;
1459
1460                                 /* Print all hits to the scrollback view, so the
1461                                  * user knows what possibilities he has.
1462                                  * Fixes #599779
1463                                  * */
1464                                  message = g_string_new ("");
1465                                  for (l = completed_list; l != NULL; l = l->next) {
1466                                         g_string_append (message, empathy_contact_get_name (l->data));
1467                                         g_string_append (message, " - ");
1468                                  }
1469                                  empathy_chat_view_append_event (chat->view, message->str);
1470                                  g_string_free (message, TRUE);
1471                         }
1472
1473                         gtk_text_buffer_insert_at_cursor (buffer, text, strlen (text));
1474
1475                         if (len == 1 && is_start_of_buffer &&
1476                             empathy_conf_get_string (empathy_conf_get (),
1477                                                      EMPATHY_PREFS_CHAT_NICK_COMPLETION_CHAR,
1478                                                      &complete_char) &&
1479                             complete_char != NULL) {
1480                                 gtk_text_buffer_insert_at_cursor (buffer,
1481                                                                   complete_char,
1482                                                                   strlen (complete_char));
1483                                 gtk_text_buffer_insert_at_cursor (buffer, " ", 1);
1484                                 g_free (complete_char);
1485                         }
1486
1487                         g_free (completed);
1488                 }
1489
1490                 g_completion_clear_items (priv->completion);
1491
1492                 g_list_foreach (list, (GFunc) g_object_unref, NULL);
1493                 g_list_free (list);
1494
1495                 return TRUE;
1496         }
1497
1498         return FALSE;
1499 }
1500
1501 static gboolean
1502 chat_text_view_focus_in_event_cb (GtkWidget  *widget,
1503                                   GdkEvent   *event,
1504                                   EmpathyChat *chat)
1505 {
1506         gtk_widget_grab_focus (chat->input_text_view);
1507
1508         return TRUE;
1509 }
1510
1511 static gboolean
1512 chat_input_set_size_request_idle (gpointer sw)
1513 {
1514         gtk_widget_set_size_request (sw, -1, MAX_INPUT_HEIGHT);
1515
1516         return FALSE;
1517 }
1518
1519 static void
1520 chat_input_size_request_cb (GtkWidget      *widget,
1521                             GtkRequisition *requisition,
1522                             EmpathyChat    *chat)
1523 {
1524         EmpathyChatPriv *priv = GET_PRIV (chat);
1525         GtkWidget       *sw;
1526
1527         sw = gtk_widget_get_parent (widget);
1528         if (requisition->height >= MAX_INPUT_HEIGHT && !priv->has_input_vscroll) {
1529                 g_idle_add (chat_input_set_size_request_idle, sw);
1530                 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw),
1531                                                 GTK_POLICY_NEVER,
1532                                                 GTK_POLICY_ALWAYS);
1533                 priv->has_input_vscroll = TRUE;
1534         }
1535
1536         if (requisition->height < MAX_INPUT_HEIGHT && priv->has_input_vscroll) {
1537                 gtk_widget_set_size_request (sw, -1, -1);
1538                 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw),
1539                                                 GTK_POLICY_NEVER,
1540                                                 GTK_POLICY_NEVER);
1541                 priv->has_input_vscroll = FALSE;
1542         }
1543 }
1544
1545 static void
1546 chat_input_realize_cb (GtkWidget   *widget,
1547                        EmpathyChat *chat)
1548 {
1549         DEBUG ("Setting focus to the input text view");
1550         if (gtk_widget_is_sensitive (widget)) {
1551                 gtk_widget_grab_focus (widget);
1552         }
1553 }
1554
1555 static void
1556 chat_insert_smiley_activate_cb (EmpathySmileyManager *manager,
1557                                 EmpathySmiley        *smiley,
1558                                 gpointer              user_data)
1559 {
1560         EmpathyChat   *chat = EMPATHY_CHAT (user_data);
1561         GtkTextBuffer *buffer;
1562         GtkTextIter    iter;
1563
1564         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1565
1566         gtk_text_buffer_get_end_iter (buffer, &iter);
1567         gtk_text_buffer_insert (buffer, &iter, smiley->str, -1);
1568
1569         gtk_text_buffer_get_end_iter (buffer, &iter);
1570         gtk_text_buffer_insert (buffer, &iter, " ", -1);
1571 }
1572
1573 typedef struct {
1574         EmpathyChat  *chat;
1575         gchar       *word;
1576
1577         GtkTextIter  start;
1578         GtkTextIter  end;
1579 } EmpathyChatSpell;
1580
1581 static EmpathyChatSpell *
1582 chat_spell_new (EmpathyChat  *chat,
1583                 const gchar *word,
1584                 GtkTextIter  start,
1585                 GtkTextIter  end)
1586 {
1587         EmpathyChatSpell *chat_spell;
1588
1589         chat_spell = g_slice_new0 (EmpathyChatSpell);
1590
1591         chat_spell->chat = g_object_ref (chat);
1592         chat_spell->word = g_strdup (word);
1593         chat_spell->start = start;
1594         chat_spell->end = end;
1595
1596         return chat_spell;
1597 }
1598
1599 static void
1600 chat_spell_free (EmpathyChatSpell *chat_spell)
1601 {
1602         g_object_unref (chat_spell->chat);
1603         g_free (chat_spell->word);
1604         g_slice_free (EmpathyChatSpell, chat_spell);
1605 }
1606
1607 static void
1608 chat_spelling_menu_activate_cb (GtkMenuItem     *menu_item,
1609                                                 EmpathyChatSpell *chat_spell)
1610 {
1611     empathy_chat_correct_word (chat_spell->chat,
1612                                &(chat_spell->start),
1613                                &(chat_spell->end),
1614                                gtk_menu_item_get_label (menu_item));
1615 }
1616
1617 static GtkWidget *
1618 chat_spelling_build_menu (EmpathyChatSpell *chat_spell)
1619 {
1620     GtkWidget *menu, *menu_item;
1621     GList     *suggestions, *l;
1622
1623     menu = gtk_menu_new ();
1624     suggestions = empathy_spell_get_suggestions (chat_spell->word);
1625     if (suggestions == NULL) {
1626         menu_item = gtk_menu_item_new_with_label (_("(No Suggestions)"));
1627         gtk_widget_set_sensitive (menu_item, FALSE);
1628         gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
1629     } else {
1630         for (l = suggestions; l; l = l->next) {
1631             menu_item = gtk_menu_item_new_with_label (l->data);
1632             g_signal_connect (G_OBJECT (menu_item),
1633                           "activate",
1634                           G_CALLBACK (chat_spelling_menu_activate_cb),
1635                           chat_spell);
1636             gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
1637         }
1638     }
1639     empathy_spell_free_suggestions (suggestions);
1640
1641     gtk_widget_show_all (menu);
1642
1643     return menu;
1644 }
1645
1646 static void
1647 chat_text_send_cb (GtkMenuItem *menuitem,
1648                    EmpathyChat *chat)
1649 {
1650         chat_input_text_view_send (chat);
1651 }
1652
1653 static void
1654 chat_input_populate_popup_cb (GtkTextView *view,
1655                               GtkMenu     *menu,
1656                               EmpathyChat *chat)
1657 {
1658         EmpathyChatPriv      *priv;
1659         GtkTextBuffer        *buffer;
1660         GtkTextTagTable      *table;
1661         GtkTextTag           *tag;
1662         gint                  x, y;
1663         GtkTextIter           iter, start, end;
1664         GtkWidget            *item;
1665         gchar                *str = NULL;
1666         EmpathyChatSpell     *chat_spell;
1667         GtkWidget            *spell_menu;
1668         EmpathySmileyManager *smiley_manager;
1669         GtkWidget            *smiley_menu;
1670         GtkWidget            *image;
1671
1672         priv = GET_PRIV (chat);
1673         buffer = gtk_text_view_get_buffer (view);
1674
1675         /* Add the emoticon menu. */
1676         item = gtk_separator_menu_item_new ();
1677         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1678         gtk_widget_show (item);
1679
1680         item = gtk_image_menu_item_new_with_mnemonic (_("Insert Smiley"));
1681         image = gtk_image_new_from_icon_name ("face-smile",
1682                                               GTK_ICON_SIZE_MENU);
1683         gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
1684         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1685         gtk_widget_show (item);
1686
1687         smiley_manager = empathy_smiley_manager_dup_singleton ();
1688         smiley_menu = empathy_smiley_menu_new (smiley_manager,
1689                                                chat_insert_smiley_activate_cb,
1690                                                chat);
1691         gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), smiley_menu);
1692         g_object_unref (smiley_manager);
1693
1694         /* Add the Send menu item. */
1695         gtk_text_buffer_get_bounds (buffer, &start, &end);
1696         str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1697         if (!EMP_STR_EMPTY (str)) {
1698                 item = gtk_menu_item_new_with_mnemonic (_("_Send"));
1699                 g_signal_connect (G_OBJECT (item), "activate",
1700                                   G_CALLBACK (chat_text_send_cb), chat);
1701                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1702                 gtk_widget_show (item);
1703         }
1704         str = NULL;
1705
1706         /* Add the spell check menu item. */
1707         table = gtk_text_buffer_get_tag_table (buffer);
1708         tag = gtk_text_tag_table_lookup (table, "misspelled");
1709         gtk_widget_get_pointer (GTK_WIDGET (view), &x, &y);
1710         gtk_text_view_window_to_buffer_coords (GTK_TEXT_VIEW (view),
1711                                                GTK_TEXT_WINDOW_WIDGET,
1712                                                x, y,
1713                                                &x, &y);
1714         gtk_text_view_get_iter_at_location (GTK_TEXT_VIEW (view), &iter, x, y);
1715         start = end = iter;
1716         if (gtk_text_iter_backward_to_tag_toggle (&start, tag) &&
1717             gtk_text_iter_forward_to_tag_toggle (&end, tag)) {
1718
1719                 str = gtk_text_buffer_get_text (buffer,
1720                                                 &start, &end, FALSE);
1721         }
1722         if (!EMP_STR_EMPTY (str)) {
1723                 chat_spell = chat_spell_new (chat, str, start, end);
1724                 g_object_set_data_full (G_OBJECT (menu),
1725                                         "chat_spell", chat_spell,
1726                                         (GDestroyNotify) chat_spell_free);
1727
1728                 item = gtk_separator_menu_item_new ();
1729                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1730                 gtk_widget_show (item);
1731
1732                 item = gtk_image_menu_item_new_with_mnemonic (_("_Spelling Suggestions"));
1733                 image = gtk_image_new_from_icon_name (GTK_STOCK_SPELL_CHECK,
1734                                                       GTK_ICON_SIZE_MENU);
1735                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
1736
1737                 spell_menu = chat_spelling_build_menu (chat_spell);
1738                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), spell_menu);
1739
1740                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1741                 gtk_widget_show (item);
1742         }
1743 }
1744
1745
1746 #ifdef ENABLE_TPL
1747 static gboolean
1748 chat_log_filter (TplLogEntry *log,
1749                  gpointer user_data)
1750 #else
1751 static gboolean
1752 chat_log_filter (EmpathyMessage *message,
1753                  gpointer user_data)
1754 #endif /* ENABLE_TPL */
1755 {
1756         EmpathyChat *chat = user_data;
1757 #ifdef ENABLE_TPL
1758         EmpathyMessage *message;
1759 #endif /* ENABLE_TPL */
1760         EmpathyChatPriv *priv = GET_PRIV (chat);
1761         const GList *pending;
1762
1763 #ifdef ENABLE_TPL
1764         g_return_val_if_fail (TPL_IS_LOG_ENTRY (log), FALSE);
1765 #else
1766         g_return_val_if_fail (EMPATHY_IS_MESSAGE (message), FALSE);
1767 #endif /* ENABLE_TPL */
1768         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
1769
1770         pending = empathy_tp_chat_get_pending_messages (priv->tp_chat);
1771 #ifdef ENABLE_TPL
1772         message = empathy_message_from_tpl_log_entry (log);
1773 #endif /* ENABLE_TPL */
1774
1775         for (; pending; pending = g_list_next (pending)) {
1776                 if (empathy_message_equal (message, pending->data)) {
1777                         return FALSE;
1778                 }
1779         }
1780 #ifdef ENABLE_TPL
1781         g_object_unref (message);
1782 #endif
1783         return TRUE;
1784 }
1785
1786
1787 static void
1788 show_pending_messages (EmpathyChat *chat) {
1789         EmpathyChatPriv *priv = GET_PRIV (chat);
1790         const GList *messages, *l;
1791
1792         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1793
1794         if (chat->view == NULL || priv->tp_chat == NULL)
1795                 return;
1796
1797         if (!priv->can_show_pending)
1798                 return;
1799
1800         messages = empathy_tp_chat_get_pending_messages (priv->tp_chat);
1801
1802         for (l = messages; l != NULL ; l = g_list_next (l)) {
1803                 EmpathyMessage *message = EMPATHY_MESSAGE (l->data);
1804                 chat_message_received (chat, message);
1805         }
1806 }
1807
1808
1809 #ifdef ENABLE_TPL
1810 static void
1811 got_filtered_messages_cb (GObject *manager,
1812                 GAsyncResult *result,
1813                 gpointer user_data)
1814 {
1815         GList *l;
1816         GList *messages;
1817         EmpathyChat *chat = EMPATHY_CHAT (user_data);
1818         EmpathyChatPriv *priv = GET_PRIV (chat);
1819         GError *error = NULL;
1820
1821         messages = tpl_log_manager_get_filtered_messages_async_finish (result, &error);
1822
1823         if (error != NULL) {
1824                 DEBUG ("%s. Aborting.", error->message);
1825                 empathy_chat_view_append_event (chat->view,
1826                         _("Failed to retrieve recent logs"));
1827                 g_error_free (error);
1828                 goto out;
1829         }
1830
1831         for (l = messages; l; l = g_list_next (l)) {
1832                 EmpathyMessage *message;
1833                 g_assert (TPL_IS_LOG_ENTRY (l->data));
1834
1835                 message = empathy_message_from_tpl_log_entry (l->data);
1836                 g_object_unref (l->data);
1837
1838                 empathy_chat_view_append_message (chat->view, message);
1839                 g_object_unref (message);
1840         }
1841         g_list_free (messages);
1842
1843 out:
1844         /* in case of TPL error, skip backlog and show pending messages */
1845         priv->can_show_pending = TRUE;
1846         show_pending_messages (chat);
1847
1848         /* FIXME: See Bug#610994, we are forcing the ACK of the queue. See comments
1849          * about it in EmpathyChatPriv definition */
1850         priv->retrieving_backlogs = FALSE;
1851         empathy_chat_messages_read (chat);
1852
1853         /* Turn back on scrolling */
1854         empathy_chat_view_scroll (chat->view, TRUE);
1855 }
1856 #endif /* ENABLE_TPL */
1857
1858
1859 static void
1860 chat_add_logs (EmpathyChat *chat)
1861 {
1862         EmpathyChatPriv *priv = GET_PRIV (chat);
1863         gboolean         is_chatroom;
1864 #ifndef ENABLE_TPL
1865         GList           *messages, *l;
1866 #endif /* ENABLE_TPL */
1867
1868         if (!priv->id) {
1869                 return;
1870         }
1871
1872         /* Turn off scrolling temporarily */
1873         empathy_chat_view_scroll (chat->view, FALSE);
1874
1875         /* Add messages from last conversation */
1876         is_chatroom = priv->handle_type == TP_HANDLE_TYPE_ROOM;
1877
1878 #ifndef ENABLE_TPL
1879         messages = empathy_log_manager_get_filtered_messages (priv->log_manager,
1880                                                               priv->account,
1881                                                               priv->id,
1882                                                               is_chatroom,
1883                                                               5,
1884                                                               chat_log_filter,
1885                                                               chat);
1886
1887         for (l = messages; l; l = g_list_next (l)) {
1888                 empathy_chat_view_append_message (chat->view, l->data);
1889                 g_object_unref (l->data);
1890         }
1891
1892         g_list_free (messages);
1893
1894         /* Turn back on scrolling */
1895         empathy_chat_view_scroll (chat->view, TRUE);
1896 #else
1897         priv->retrieving_backlogs = TRUE;
1898         tpl_log_manager_get_filtered_messages_async (priv->log_manager,
1899                                                               priv->account,
1900                                                               priv->id,
1901                                                               is_chatroom,
1902                                                               5,
1903                                                               chat_log_filter,
1904                                                               chat,
1905                                                               got_filtered_messages_cb,
1906                                                               (gpointer) chat);
1907 #endif /* ENABLE_TPL */
1908 }
1909
1910 static gint
1911 chat_contacts_completion_func (const gchar *s1,
1912                                const gchar *s2,
1913                                gsize        n)
1914 {
1915         gchar *tmp, *nick1, *nick2;
1916         gint   ret;
1917
1918         if (s1 == s2) {
1919                 return 0;
1920         }
1921         if (!s1 || !s2) {
1922                 return s1 ? -1 : +1;
1923         }
1924
1925         tmp = g_utf8_normalize (s1, -1, G_NORMALIZE_DEFAULT);
1926         nick1 = g_utf8_casefold (tmp, -1);
1927         g_free (tmp);
1928
1929         tmp = g_utf8_normalize (s2, -1, G_NORMALIZE_DEFAULT);
1930         nick2 = g_utf8_casefold (tmp, -1);
1931         g_free (tmp);
1932
1933         ret = strncmp (nick1, nick2, n);
1934
1935         g_free (nick1);
1936         g_free (nick2);
1937
1938         return ret;
1939 }
1940
1941 static gchar *
1942 build_part_message (guint           reason,
1943                     const gchar    *name,
1944                     EmpathyContact *actor,
1945                     const gchar    *message)
1946 {
1947         GString *s = g_string_new ("");
1948         const gchar *actor_name = NULL;
1949
1950         if (actor != NULL) {
1951                 actor_name = empathy_contact_get_name (actor);
1952         }
1953
1954         /* Having an actor only really makes sense for a few actions... */
1955         switch (reason) {
1956         case TP_CHANNEL_GROUP_CHANGE_REASON_OFFLINE:
1957                 g_string_append_printf (s, _("%s has disconnected"), name);
1958                 break;
1959         case TP_CHANNEL_GROUP_CHANGE_REASON_KICKED:
1960                 if (actor_name != NULL) {
1961                         /* translators: reverse the order of these arguments
1962                          * if the kicked should come before the kicker in your locale.
1963                          */
1964                         g_string_append_printf (s, _("%1$s was kicked by %2$s"),
1965                                 name, actor_name);
1966                 } else {
1967                         g_string_append_printf (s, _("%s was kicked"), name);
1968                 }
1969                 break;
1970         case TP_CHANNEL_GROUP_CHANGE_REASON_BANNED:
1971                 if (actor_name != NULL) {
1972                         /* translators: reverse the order of these arguments
1973                          * if the banned should come before the banner in your locale.
1974                          */
1975                         g_string_append_printf (s, _("%1$s was banned by %2$s"),
1976                                 name, actor_name);
1977                 } else {
1978                         g_string_append_printf (s, _("%s was banned"), name);
1979                 }
1980                 break;
1981         default:
1982                 g_string_append_printf (s, _("%s has left the room"), name);
1983         }
1984
1985         if (!EMP_STR_EMPTY (message)) {
1986                 /* Note to translators: this string is appended to
1987                  * notifications like "foo has left the room", with the message
1988                  * given by the user living the room. If this poses a problem,
1989                  * please let us know. :-)
1990                  */
1991                 g_string_append_printf (s, _(" (%s)"), message);
1992         }
1993
1994         return g_string_free (s, FALSE);
1995 }
1996
1997 static void
1998 chat_members_changed_cb (EmpathyTpChat  *tp_chat,
1999                          EmpathyContact *contact,
2000                          EmpathyContact *actor,
2001                          guint           reason,
2002                          gchar          *message,
2003                          gboolean        is_member,
2004                          EmpathyChat    *chat)
2005 {
2006         EmpathyChatPriv *priv = GET_PRIV (chat);
2007         const gchar *name = empathy_contact_get_name (contact);
2008         gchar *str;
2009
2010         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED != reason);
2011
2012         if (priv->block_events_timeout_id != 0)
2013                 return;
2014
2015         if (is_member) {
2016                 str = g_strdup_printf (_("%s has joined the room"),
2017                                        name);
2018         } else {
2019                 str = build_part_message (reason, name, actor, message);
2020         }
2021
2022         empathy_chat_view_append_event (chat->view, str);
2023         g_free (str);
2024 }
2025
2026 static void
2027 chat_member_renamed_cb (EmpathyTpChat  *tp_chat,
2028                          EmpathyContact *old_contact,
2029                          EmpathyContact *new_contact,
2030                          guint           reason,
2031                          gchar          *message,
2032                          EmpathyChat    *chat)
2033 {
2034         EmpathyChatPriv *priv = GET_PRIV (chat);
2035
2036         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED == reason);
2037
2038         if (priv->block_events_timeout_id == 0) {
2039                 gchar *str;
2040
2041                 str = g_strdup_printf (_("%s is now known as %s"),
2042                                        empathy_contact_get_name (old_contact),
2043                                        empathy_contact_get_name (new_contact));
2044                 empathy_chat_view_append_event (chat->view, str);
2045                 g_free (str);
2046         }
2047
2048 }
2049
2050 static gboolean
2051 chat_reset_size_request (gpointer widget)
2052 {
2053         gtk_widget_set_size_request (widget, -1, -1);
2054
2055         return FALSE;
2056 }
2057
2058 static void
2059 chat_update_contacts_visibility (EmpathyChat *chat,
2060                          gboolean show)
2061 {
2062         EmpathyChatPriv *priv = GET_PRIV (chat);
2063         GtkAllocation allocation;
2064
2065         if (!priv->scrolled_window_contacts) {
2066                 return;
2067         }
2068
2069         if (priv->remote_contact != NULL) {
2070                 show = FALSE;
2071         }
2072
2073         if (show && priv->contact_list_view == NULL) {
2074                 EmpathyContactListStore *store;
2075                 gint                     min_width;
2076
2077                 /* We are adding the contact list to the chat, we don't want the
2078                  * chat view to become too small. If the chat view is already
2079                  * smaller than 250 make sure that size won't change. If the
2080                  * chat view is bigger the contact list will take some space on
2081                  * it but we make sure the chat view don't become smaller than
2082                  * 250. Relax the size request once the resize is done */
2083                 gtk_widget_get_allocation (priv->vbox_left, &allocation);
2084                 min_width = MIN (allocation.width, 250);
2085                 gtk_widget_set_size_request (priv->vbox_left, min_width, -1);
2086                 g_idle_add (chat_reset_size_request, priv->vbox_left);
2087
2088                 if (priv->contacts_width > 0) {
2089                         gtk_paned_set_position (GTK_PANED (priv->hpaned),
2090                                                 priv->contacts_width);
2091                 }
2092
2093                 store = empathy_contact_list_store_new (
2094                                 EMPATHY_CONTACT_LIST (priv->tp_chat));
2095                 empathy_contact_list_store_set_show_groups (
2096                                 EMPATHY_CONTACT_LIST_STORE (store), FALSE);
2097
2098                 priv->contact_list_view = GTK_WIDGET (empathy_contact_list_view_new (store,
2099                         EMPATHY_CONTACT_LIST_FEATURE_CONTACT_TOOLTIP,
2100                         EMPATHY_CONTACT_FEATURE_CHAT |
2101                         EMPATHY_CONTACT_FEATURE_CALL |
2102                         EMPATHY_CONTACT_FEATURE_LOG |
2103                         EMPATHY_CONTACT_FEATURE_INFO));
2104                 gtk_container_add (GTK_CONTAINER (priv->scrolled_window_contacts),
2105                                    priv->contact_list_view);
2106                 gtk_widget_show (priv->contact_list_view);
2107                 gtk_widget_show (priv->scrolled_window_contacts);
2108                 g_object_unref (store);
2109         } else if (!show) {
2110                 priv->contacts_width = gtk_paned_get_position (GTK_PANED (priv->hpaned));
2111                 gtk_widget_hide (priv->scrolled_window_contacts);
2112                 if (priv->contact_list_view != NULL) {
2113                         gtk_widget_destroy (priv->contact_list_view);
2114                         priv->contact_list_view = NULL;
2115                 }
2116         }
2117 }
2118
2119 void
2120 empathy_chat_set_show_contacts (EmpathyChat *chat,
2121                                 gboolean     show)
2122 {
2123         EmpathyChatPriv *priv = GET_PRIV (chat);
2124
2125         priv->show_contacts = show;
2126
2127         chat_update_contacts_visibility (chat, show);
2128
2129         g_object_notify (G_OBJECT (chat), "show-contacts");
2130 }
2131
2132 static void
2133 chat_remote_contact_changed_cb (EmpathyChat *chat)
2134 {
2135         EmpathyChatPriv *priv = GET_PRIV (chat);
2136
2137         if (priv->remote_contact != NULL) {
2138                 g_object_unref (priv->remote_contact);
2139                 priv->remote_contact = NULL;
2140         }
2141
2142         g_free (priv->id);
2143
2144         priv->id = g_strdup (empathy_tp_chat_get_id (priv->tp_chat));
2145         priv->remote_contact = empathy_tp_chat_get_remote_contact (priv->tp_chat);
2146         if (priv->remote_contact != NULL) {
2147                 g_object_ref (priv->remote_contact);
2148                 priv->handle_type = TP_HANDLE_TYPE_CONTACT;
2149         }
2150         else if (priv->tp_chat != NULL) {
2151                 TpChannel *channel;
2152
2153                 channel = empathy_tp_chat_get_channel (priv->tp_chat);
2154                 g_object_get (channel, "handle-type", &priv->handle_type, NULL);
2155         }
2156
2157         chat_update_contacts_visibility (chat, priv->show_contacts);
2158
2159         g_object_notify (G_OBJECT (chat), "remote-contact");
2160         g_object_notify (G_OBJECT (chat), "id");
2161 }
2162
2163 static void
2164 chat_destroy_cb (EmpathyTpChat *tp_chat,
2165                  EmpathyChat   *chat)
2166 {
2167         EmpathyChatPriv *priv;
2168
2169         priv = GET_PRIV (chat);
2170
2171         if (!priv->tp_chat) {
2172                 return;
2173         }
2174
2175         chat_composing_remove_timeout (chat);
2176         g_object_unref (priv->tp_chat);
2177         priv->tp_chat = NULL;
2178         g_object_notify (G_OBJECT (chat), "tp-chat");
2179
2180         empathy_chat_view_append_event (chat->view, _("Disconnected"));
2181         gtk_widget_set_sensitive (chat->input_text_view, FALSE);
2182
2183         chat_update_contacts_visibility (chat, FALSE);
2184 }
2185
2186 static gboolean
2187 chat_hpaned_pos_changed_cb (GtkWidget* hpaned, gpointer user_data)
2188 {
2189         gint hpaned_pos;
2190         hpaned_pos = gtk_paned_get_position (GTK_PANED(hpaned));
2191         empathy_conf_set_int (empathy_conf_get (),
2192                               EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS,
2193                               hpaned_pos);
2194         return TRUE;
2195 }
2196
2197 static void
2198 chat_create_ui (EmpathyChat *chat)
2199 {
2200         EmpathyChatPriv *priv = GET_PRIV (chat);
2201         GtkBuilder      *gui;
2202         GList           *list = NULL;
2203         gchar           *filename;
2204         GtkTextBuffer   *buffer;
2205         gint              paned_pos;
2206
2207         filename = empathy_file_lookup ("empathy-chat.ui",
2208                                         "libempathy-gtk");
2209         gui = empathy_builder_get_file (filename,
2210                                         "chat_widget", &priv->widget,
2211                                         "hpaned", &priv->hpaned,
2212                                         "vbox_left", &priv->vbox_left,
2213                                         "scrolled_window_chat", &priv->scrolled_window_chat,
2214                                         "scrolled_window_input", &priv->scrolled_window_input,
2215                                         "hbox_topic", &priv->hbox_topic,
2216                                         "label_topic", &priv->label_topic,
2217                                         "scrolled_window_contacts", &priv->scrolled_window_contacts,
2218                                         "info_bar_vbox", &priv->info_bar_vbox,
2219                                         NULL);
2220         g_free (filename);
2221
2222         /* Add message view. */
2223         chat->view = empathy_theme_manager_create_view (empathy_theme_manager_get ());
2224         /* If this is a GtkTextView, it's set as a drag destination for text/plain
2225            and other types, even though it's non-editable and doesn't accept any
2226            drags.  This steals drag motion for anything inside the scrollbars,
2227            making drag destinations on chat windows far less useful.
2228          */
2229         gtk_drag_dest_unset (GTK_WIDGET (chat->view));
2230         g_signal_connect (chat->view, "focus_in_event",
2231                           G_CALLBACK (chat_text_view_focus_in_event_cb),
2232                           chat);
2233         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_chat),
2234                            GTK_WIDGET (chat->view));
2235         gtk_widget_show (GTK_WIDGET (chat->view));
2236
2237         /* Add input GtkTextView */
2238         chat->input_text_view = g_object_new (GTK_TYPE_TEXT_VIEW,
2239                                               "pixels-above-lines", 2,
2240                                               "pixels-below-lines", 2,
2241                                               "pixels-inside-wrap", 1,
2242                                               "right-margin", 2,
2243                                               "left-margin", 2,
2244                                               "wrap-mode", GTK_WRAP_WORD_CHAR,
2245                                               NULL);
2246         g_signal_connect (chat->input_text_view, "key-press-event",
2247                           G_CALLBACK (chat_input_key_press_event_cb),
2248                           chat);
2249         g_signal_connect (chat->input_text_view, "size-request",
2250                           G_CALLBACK (chat_input_size_request_cb),
2251                           chat);
2252         g_signal_connect (chat->input_text_view, "realize",
2253                           G_CALLBACK (chat_input_realize_cb),
2254                           chat);
2255         g_signal_connect (chat->input_text_view, "populate-popup",
2256                           G_CALLBACK (chat_input_populate_popup_cb),
2257                           chat);
2258         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2259         empathy_signal_connect_weak  (buffer, "changed",
2260                           G_CALLBACK (chat_input_text_buffer_changed_cb),
2261                           G_OBJECT (chat));
2262         gtk_text_buffer_create_tag (buffer, "misspelled",
2263                                     "underline", PANGO_UNDERLINE_ERROR,
2264                                     NULL);
2265         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_input),
2266                            chat->input_text_view);
2267         gtk_widget_show (chat->input_text_view);
2268
2269         /* Add the (invisible) search bar */
2270         priv->search_bar = empathy_search_bar_new (chat->view);
2271         gtk_box_pack_start (GTK_BOX(priv->vbox_left),
2272                             priv->search_bar,
2273                             FALSE, FALSE, 0);
2274         gtk_box_reorder_child (GTK_BOX(priv->vbox_left), priv->search_bar, 1);
2275
2276         /* Initialy hide the topic, will be shown if not empty */
2277         gtk_widget_hide (priv->hbox_topic);
2278
2279         g_signal_connect (priv->hpaned, "notify::position",
2280                           G_CALLBACK (chat_hpaned_pos_changed_cb),
2281                           NULL);
2282
2283         /* Load the paned position */
2284         if (empathy_conf_get_int (empathy_conf_get (),
2285                                  EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS,
2286                                  &paned_pos)
2287                 && paned_pos)
2288                 gtk_paned_set_position (GTK_PANED(priv->hpaned), paned_pos);
2289
2290         /* Set widget focus order */
2291         list = g_list_append (NULL, priv->search_bar);
2292         list = g_list_append (list, priv->scrolled_window_input);
2293         gtk_container_set_focus_chain (GTK_CONTAINER (priv->vbox_left), list);
2294         g_list_free (list);
2295
2296         list = g_list_append (NULL, priv->vbox_left);
2297         list = g_list_append (list, priv->scrolled_window_contacts);
2298         gtk_container_set_focus_chain (GTK_CONTAINER (priv->hpaned), list);
2299         g_list_free (list);
2300
2301         list = g_list_append (NULL, priv->hpaned);
2302         list = g_list_append (list, priv->hbox_topic);
2303         gtk_container_set_focus_chain (GTK_CONTAINER (priv->widget), list);
2304         g_list_free (list);
2305
2306         /* Add the main widget in the chat widget */
2307         gtk_container_add (GTK_CONTAINER (chat), priv->widget);
2308         g_object_unref (gui);
2309 }
2310
2311 static void
2312 chat_size_request (GtkWidget      *widget,
2313                    GtkRequisition *requisition)
2314 {
2315   GtkBin *bin = GTK_BIN (widget);
2316   GtkWidget *child;
2317
2318   requisition->width = gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2;
2319   requisition->height = gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2;
2320
2321   child = gtk_bin_get_child (bin);
2322
2323   if (child && gtk_widget_get_visible (child))
2324     {
2325       GtkRequisition child_requisition;
2326
2327       gtk_widget_size_request (child, &child_requisition);
2328
2329       requisition->width += child_requisition.width;
2330       requisition->height += child_requisition.height;
2331     }
2332 }
2333
2334 static void
2335 chat_size_allocate (GtkWidget     *widget,
2336                     GtkAllocation *allocation)
2337 {
2338   GtkBin *bin = GTK_BIN (widget);
2339   GtkAllocation child_allocation;
2340   GtkWidget *child;
2341
2342   gtk_widget_set_allocation (widget, allocation);
2343
2344   child = gtk_bin_get_child (bin);
2345
2346   if (child && gtk_widget_get_visible (child))
2347     {
2348       child_allocation.x = allocation->x + gtk_container_get_border_width (GTK_CONTAINER (widget));
2349       child_allocation.y = allocation->y + gtk_container_get_border_width (GTK_CONTAINER (widget));
2350       child_allocation.width = MAX (allocation->width - gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2, 0);
2351       child_allocation.height = MAX (allocation->height - gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2, 0);
2352
2353       gtk_widget_size_allocate (child, &child_allocation);
2354     }
2355 }
2356
2357 static void
2358 chat_finalize (GObject *object)
2359 {
2360         EmpathyChat     *chat;
2361         EmpathyChatPriv *priv;
2362
2363         chat = EMPATHY_CHAT (object);
2364         priv = GET_PRIV (chat);
2365
2366         DEBUG ("Finalized: %p", object);
2367
2368         g_list_foreach (priv->input_history, (GFunc) chat_input_history_entry_free, NULL);
2369         g_list_free (priv->input_history);
2370
2371         g_list_foreach (priv->compositors, (GFunc) g_object_unref, NULL);
2372         g_list_free (priv->compositors);
2373
2374         chat_composing_remove_timeout (chat);
2375
2376         g_object_unref (priv->account_manager);
2377         g_object_unref (priv->log_manager);
2378
2379         if (priv->tp_chat) {
2380                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2381                         chat_destroy_cb, chat);
2382                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2383                         chat_message_received_cb, chat);
2384                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2385                         chat_send_error_cb, chat);
2386                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2387                         chat_state_changed_cb, chat);
2388                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2389                         chat_property_changed_cb, chat);
2390                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2391                         chat_members_changed_cb, chat);
2392                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2393                         chat_remote_contact_changed_cb, chat);
2394                 empathy_tp_chat_leave (priv->tp_chat);
2395                 g_object_unref (priv->tp_chat);
2396         }
2397         if (priv->account) {
2398                 g_object_unref (priv->account);
2399         }
2400         if (priv->remote_contact) {
2401                 g_object_unref (priv->remote_contact);
2402         }
2403
2404         if (priv->block_events_timeout_id) {
2405                 g_source_remove (priv->block_events_timeout_id);
2406         }
2407
2408         g_free (priv->id);
2409         g_free (priv->name);
2410         g_free (priv->subject);
2411         g_completion_free (priv->completion);
2412
2413         G_OBJECT_CLASS (empathy_chat_parent_class)->finalize (object);
2414 }
2415
2416 static void
2417 chat_constructed (GObject *object)
2418 {
2419         EmpathyChat *chat = EMPATHY_CHAT (object);
2420         EmpathyChatPriv *priv = GET_PRIV (chat);
2421
2422         if (priv->handle_type != TP_HANDLE_TYPE_ROOM)
2423                 chat_add_logs (chat);
2424 #ifndef ENABLE_TPL
2425         /* When async API are involved, pending message are shown at the end of the
2426          * callbacks' chain fired by chat_add_logs */
2427         priv->can_show_pending = TRUE;
2428         show_pending_messages (chat);
2429 #endif /* ENABLE_TPL */
2430 }
2431
2432 static void
2433 empathy_chat_class_init (EmpathyChatClass *klass)
2434 {
2435         GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
2436         GObjectClass   *object_class = G_OBJECT_CLASS (klass);
2437
2438         object_class->finalize = chat_finalize;
2439         object_class->get_property = chat_get_property;
2440         object_class->set_property = chat_set_property;
2441         object_class->constructed = chat_constructed;
2442
2443         widget_class->size_request = chat_size_request;
2444         widget_class->size_allocate = chat_size_allocate;
2445
2446         g_object_class_install_property (object_class,
2447                                          PROP_TP_CHAT,
2448                                          g_param_spec_object ("tp-chat",
2449                                                               "Empathy tp chat",
2450                                                               "The tp chat object",
2451                                                               EMPATHY_TYPE_TP_CHAT,
2452                                                               G_PARAM_CONSTRUCT |
2453                                                               G_PARAM_READWRITE |
2454                                                               G_PARAM_STATIC_STRINGS));
2455         g_object_class_install_property (object_class,
2456                                          PROP_ACCOUNT,
2457                                          g_param_spec_object ("account",
2458                                                               "Account of the chat",
2459                                                               "The account of the chat",
2460                                                               TP_TYPE_ACCOUNT,
2461                                                               G_PARAM_READABLE |
2462                                                               G_PARAM_STATIC_STRINGS));
2463         g_object_class_install_property (object_class,
2464                                          PROP_ID,
2465                                          g_param_spec_string ("id",
2466                                                               "Chat's id",
2467                                                               "The id of the chat",
2468                                                               NULL,
2469                                                               G_PARAM_READABLE |
2470                                                               G_PARAM_STATIC_STRINGS));
2471         g_object_class_install_property (object_class,
2472                                          PROP_NAME,
2473                                          g_param_spec_string ("name",
2474                                                               "Chat's name",
2475                                                               "The name of the chat",
2476                                                               NULL,
2477                                                               G_PARAM_READABLE |
2478                                                               G_PARAM_STATIC_STRINGS));
2479         g_object_class_install_property (object_class,
2480                                          PROP_SUBJECT,
2481                                          g_param_spec_string ("subject",
2482                                                               "Chat's subject",
2483                                                               "The subject or topic of the chat",
2484                                                               NULL,
2485                                                               G_PARAM_READABLE |
2486                                                               G_PARAM_STATIC_STRINGS));
2487         g_object_class_install_property (object_class,
2488                                          PROP_REMOTE_CONTACT,
2489                                          g_param_spec_object ("remote-contact",
2490                                                               "The remote contact",
2491                                                               "The remote contact is any",
2492                                                               EMPATHY_TYPE_CONTACT,
2493                                                               G_PARAM_READABLE |
2494                                                               G_PARAM_STATIC_STRINGS));
2495         g_object_class_install_property (object_class,
2496                                          PROP_SHOW_CONTACTS,
2497                                          g_param_spec_boolean ("show-contacts",
2498                                                                "Contacts' visibility",
2499                                                                "The visibility of the contacts' list",
2500                                                                TRUE,
2501                                                                G_PARAM_READWRITE |
2502                                                                G_PARAM_STATIC_STRINGS));
2503
2504         signals[COMPOSING] =
2505                 g_signal_new ("composing",
2506                               G_OBJECT_CLASS_TYPE (object_class),
2507                               G_SIGNAL_RUN_LAST,
2508                               0,
2509                               NULL, NULL,
2510                               g_cclosure_marshal_VOID__BOOLEAN,
2511                               G_TYPE_NONE,
2512                               1, G_TYPE_BOOLEAN);
2513
2514         signals[NEW_MESSAGE] =
2515                 g_signal_new ("new-message",
2516                               G_OBJECT_CLASS_TYPE (object_class),
2517                               G_SIGNAL_RUN_LAST,
2518                               0,
2519                               NULL, NULL,
2520                               g_cclosure_marshal_VOID__OBJECT,
2521                               G_TYPE_NONE,
2522                               1, EMPATHY_TYPE_MESSAGE);
2523
2524         g_type_class_add_private (object_class, sizeof (EmpathyChatPriv));
2525 }
2526
2527 static gboolean
2528 chat_block_events_timeout_cb (gpointer data)
2529 {
2530         EmpathyChatPriv *priv = GET_PRIV (data);
2531
2532         priv->block_events_timeout_id = 0;
2533
2534         return FALSE;
2535 }
2536
2537 static void
2538 account_manager_prepared_cb (GObject *source_object,
2539                              GAsyncResult *result,
2540                              gpointer user_data)
2541 {
2542         GList *accounts, *l;
2543         TpAccountManager *account_manager = TP_ACCOUNT_MANAGER (source_object);
2544         EmpathyChat *chat = user_data;
2545         GError *error = NULL;
2546
2547         if (!tp_account_manager_prepare_finish (account_manager, result, &error)) {
2548                 DEBUG ("Failed to prepare the account manager: %s", error->message);
2549                 g_error_free (error);
2550                 return;
2551         }
2552
2553         accounts = tp_account_manager_get_valid_accounts (account_manager);
2554
2555         for (l = accounts; l != NULL; l = l->next) {
2556                 TpAccount *account = l->data;
2557                 empathy_signal_connect_weak (account, "status-changed",
2558                                              G_CALLBACK (chat_new_connection_cb),
2559                                              G_OBJECT (chat));
2560         }
2561
2562         g_list_free (accounts);
2563 }
2564
2565 static void
2566 empathy_chat_init (EmpathyChat *chat)
2567 {
2568         EmpathyChatPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chat,
2569                 EMPATHY_TYPE_CHAT, EmpathyChatPriv);
2570
2571         chat->priv = priv;
2572 #ifndef ENABLE_TPL
2573         priv->log_manager = empathy_log_manager_dup_singleton ();
2574 #else
2575         priv->log_manager = tpl_log_manager_dup_singleton ();
2576 #endif /* ENABLE_TPL */
2577         priv->contacts_width = -1;
2578         priv->input_history = NULL;
2579         priv->input_history_current = NULL;
2580         priv->account_manager = tp_account_manager_dup ();
2581
2582         tp_account_manager_prepare_async (priv->account_manager, NULL,
2583                                           account_manager_prepared_cb, chat);
2584
2585         empathy_conf_get_bool (empathy_conf_get (),
2586                                EMPATHY_PREFS_CHAT_SHOW_CONTACTS_IN_ROOMS,
2587                                &priv->show_contacts);
2588
2589         /* Block events for some time to avoid having "has come online" or
2590          * "joined" messages. */
2591         priv->block_events_timeout_id =
2592                 g_timeout_add_seconds (1, chat_block_events_timeout_cb, chat);
2593
2594         /* Add nick name completion */
2595         priv->completion = g_completion_new ((GCompletionFunc) empathy_contact_get_name);
2596         g_completion_set_compare (priv->completion, chat_contacts_completion_func);
2597
2598         chat_create_ui (chat);
2599 }
2600
2601 EmpathyChat *
2602 empathy_chat_new (EmpathyTpChat *tp_chat)
2603 {
2604         return g_object_new (EMPATHY_TYPE_CHAT, "tp-chat", tp_chat, NULL);
2605 }
2606
2607 EmpathyTpChat *
2608 empathy_chat_get_tp_chat (EmpathyChat *chat)
2609 {
2610         EmpathyChatPriv *priv = GET_PRIV (chat);
2611
2612         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2613
2614         return priv->tp_chat;
2615 }
2616
2617 static void display_password_info_bar (EmpathyChat *self,
2618                                        gboolean retry);
2619
2620 static void
2621 provide_password_cb (GObject *tp_chat,
2622                      GAsyncResult *res,
2623                      gpointer user_data)
2624 {
2625         EmpathyChat *self = EMPATHY_CHAT (user_data);
2626         EmpathyChatPriv *priv = GET_PRIV (self);
2627         GError *error = NULL;
2628
2629         if (!empathy_tp_chat_provide_password_finish (EMPATHY_TP_CHAT (tp_chat), res,
2630                                                       &error)) {
2631                 DEBUG ("error: %s", error->message);
2632                 /* FIXME: what should we do if that's another error? Close the channel?
2633                  * Display the raw D-Bus error to the user isn't very useful */
2634                 if (g_error_matches (error, TP_ERRORS, TP_ERROR_AUTHENTICATION_FAILED))
2635                         display_password_info_bar (self, TRUE);
2636                 g_error_free (error);
2637                 return;
2638         }
2639
2640         /* Room joined */
2641         gtk_widget_set_sensitive (priv->hpaned, TRUE);
2642         gtk_widget_grab_focus (self->input_text_view);
2643 }
2644
2645 static void
2646 password_infobar_response_cb (GtkWidget *info_bar,
2647                               gint response_id,
2648                               EmpathyChat *self)
2649 {
2650         EmpathyChatPriv *priv = GET_PRIV (self);
2651         GtkWidget *entry;
2652         const gchar *password;
2653
2654         if (response_id != GTK_RESPONSE_OK)
2655                 goto out;
2656
2657         entry = g_object_get_data (G_OBJECT (info_bar), "password-entry");
2658         g_assert (entry != NULL);
2659
2660         password = gtk_entry_get_text (GTK_ENTRY (entry));
2661
2662         empathy_tp_chat_provide_password_async (priv->tp_chat, password,
2663                                                 provide_password_cb, self);
2664
2665  out:
2666         gtk_widget_destroy (info_bar);
2667 }
2668
2669 static void
2670 password_entry_activate_cb (GtkWidget *entry,
2671                           GtkWidget *info_bar)
2672 {
2673         gtk_info_bar_response (GTK_INFO_BAR (info_bar), GTK_RESPONSE_OK);
2674 }
2675
2676 static void
2677 passwd_join_button_cb (GtkButton *button,
2678                           GtkWidget *info_bar)
2679 {
2680         gtk_info_bar_response (GTK_INFO_BAR (info_bar), GTK_RESPONSE_OK);
2681 }
2682
2683 static void
2684 display_password_info_bar (EmpathyChat *self,
2685                            gboolean retry)
2686 {
2687         EmpathyChatPriv *priv = GET_PRIV (self);
2688         GtkWidget *info_bar;
2689         GtkWidget *content_area;
2690         GtkWidget *hbox;
2691         GtkWidget *image;
2692         GtkWidget *label;
2693         GtkWidget *entry;
2694         GtkWidget *alig;
2695         GtkWidget *button;
2696         GtkMessageType type;
2697         const gchar *msg, *button_label;
2698
2699         if (retry) {
2700                 /* Previous password was wrong */
2701                 type = GTK_MESSAGE_ERROR;
2702                 msg = _("Wrong password; please try again:");
2703                 button_label = _("Retry");
2704         }
2705         else {
2706                 /* First time we're trying to join */
2707                 type = GTK_MESSAGE_QUESTION;
2708                 msg = _("This room is protected by a password:");
2709                 button_label = _("Join");
2710         }
2711
2712         info_bar = gtk_info_bar_new ();
2713         gtk_info_bar_set_message_type (GTK_INFO_BAR (info_bar), type);
2714
2715         content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (info_bar));
2716
2717         hbox = gtk_hbox_new (FALSE, 3);
2718         gtk_container_add (GTK_CONTAINER (content_area), hbox);
2719
2720         /* Add image */
2721         image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_AUTHENTICATION,
2722                                           GTK_ICON_SIZE_DIALOG);
2723         gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
2724
2725         /* Add message */
2726         label = gtk_label_new (msg);
2727         gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);
2728
2729         /* Add password entry */
2730         entry = gtk_entry_new ();
2731         gtk_entry_set_visibility (GTK_ENTRY (entry), FALSE);
2732         gtk_box_pack_start (GTK_BOX (hbox), entry, TRUE, TRUE, 0);
2733
2734         g_signal_connect (entry, "activate",
2735                           G_CALLBACK (password_entry_activate_cb), info_bar);
2736
2737         /* Focus the password entry once it's realized */
2738         g_signal_connect (entry, "realize", G_CALLBACK (gtk_widget_grab_focus), NULL);
2739
2740         /* Add 'Join' button */
2741         alig = gtk_alignment_new (0, 0.5, 0, 0);
2742
2743         button = gtk_button_new_with_label (button_label);
2744         gtk_container_add (GTK_CONTAINER (alig), button);
2745         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
2746
2747         g_signal_connect (button, "clicked", G_CALLBACK (passwd_join_button_cb),
2748                           info_bar);
2749
2750         g_object_set_data (G_OBJECT (info_bar), "password-entry", entry);
2751
2752         gtk_box_pack_start (GTK_BOX (priv->info_bar_vbox), info_bar,
2753                             FALSE, FALSE, 3);
2754         gtk_widget_show_all (hbox);
2755
2756         g_signal_connect (info_bar, "response",
2757                           G_CALLBACK (password_infobar_response_cb), self);
2758
2759         gtk_widget_show_all (info_bar);
2760 }
2761
2762 static void
2763 chat_password_needed_changed_cb (EmpathyChat *self)
2764 {
2765         EmpathyChatPriv *priv = GET_PRIV (self);
2766
2767         if (empathy_tp_chat_password_needed (priv->tp_chat)) {
2768                 display_password_info_bar (self, FALSE);
2769                 gtk_widget_set_sensitive (priv->hpaned, FALSE);
2770         }
2771 }
2772
2773 void
2774 empathy_chat_set_tp_chat (EmpathyChat   *chat,
2775                           EmpathyTpChat *tp_chat)
2776 {
2777         EmpathyChatPriv *priv = GET_PRIV (chat);
2778         TpConnection    *connection;
2779         GPtrArray       *properties;
2780
2781         g_return_if_fail (EMPATHY_IS_CHAT (chat));
2782         g_return_if_fail (EMPATHY_IS_TP_CHAT (tp_chat));
2783         g_return_if_fail (empathy_tp_chat_is_ready (tp_chat));
2784
2785         if (priv->tp_chat) {
2786                 return;
2787         }
2788
2789         if (priv->account) {
2790                 g_object_unref (priv->account);
2791         }
2792
2793         priv->tp_chat = g_object_ref (tp_chat);
2794         connection = empathy_tp_chat_get_connection (priv->tp_chat);
2795         priv->account = g_object_ref (empathy_get_account_for_connection (connection));
2796
2797         g_signal_connect (tp_chat, "destroy",
2798                           G_CALLBACK (chat_destroy_cb),
2799                           chat);
2800         g_signal_connect (tp_chat, "message-received",
2801                           G_CALLBACK (chat_message_received_cb),
2802                           chat);
2803         g_signal_connect (tp_chat, "send-error",
2804                           G_CALLBACK (chat_send_error_cb),
2805                           chat);
2806         g_signal_connect (tp_chat, "chat-state-changed",
2807                           G_CALLBACK (chat_state_changed_cb),
2808                           chat);
2809         g_signal_connect (tp_chat, "property-changed",
2810                           G_CALLBACK (chat_property_changed_cb),
2811                           chat);
2812         g_signal_connect (tp_chat, "members-changed",
2813                           G_CALLBACK (chat_members_changed_cb),
2814                           chat);
2815         g_signal_connect (tp_chat, "member-renamed",
2816                           G_CALLBACK (chat_member_renamed_cb),
2817                           chat);
2818         g_signal_connect_swapped (tp_chat, "notify::remote-contact",
2819                                   G_CALLBACK (chat_remote_contact_changed_cb),
2820                                   chat);
2821         g_signal_connect_swapped (tp_chat, "notify::password-needed",
2822                                   G_CALLBACK (chat_password_needed_changed_cb),
2823                                   chat);
2824
2825         /* Get initial value of properties */
2826         properties = empathy_tp_chat_get_properties (priv->tp_chat);
2827         if (properties != NULL) {
2828                 guint i;
2829
2830                 for (i = 0; i < properties->len; i++) {
2831                         EmpathyTpChatProperty *property;
2832
2833                         property = g_ptr_array_index (properties, i);
2834                         if (property->value == NULL)
2835                                 continue;
2836
2837                         chat_property_changed_cb (priv->tp_chat,
2838                                                   property->name,
2839                                                   property->value,
2840                                                   chat);
2841                 }
2842         }
2843
2844         chat_remote_contact_changed_cb (chat);
2845
2846         if (chat->input_text_view) {
2847                 gtk_widget_set_sensitive (chat->input_text_view, TRUE);
2848                 if (priv->block_events_timeout_id == 0) {
2849                         empathy_chat_view_append_event (chat->view, _("Connected"));
2850                 }
2851         }
2852
2853         g_object_notify (G_OBJECT (chat), "tp-chat");
2854         g_object_notify (G_OBJECT (chat), "id");
2855         g_object_notify (G_OBJECT (chat), "account");
2856
2857         /* This is a noop when tp-chat is set at object construction time and causes
2858          * the pending messages to be show when it's set on the object after it has
2859          * been created */
2860         show_pending_messages (chat);
2861
2862         /* check if a password is needed */
2863         chat_password_needed_changed_cb (chat);
2864 }
2865
2866 TpAccount *
2867 empathy_chat_get_account (EmpathyChat *chat)
2868 {
2869         EmpathyChatPriv *priv = GET_PRIV (chat);
2870
2871         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2872
2873         return priv->account;
2874 }
2875
2876 const gchar *
2877 empathy_chat_get_id (EmpathyChat *chat)
2878 {
2879         EmpathyChatPriv *priv = GET_PRIV (chat);
2880
2881         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2882
2883         return priv->id;
2884 }
2885
2886 const gchar *
2887 empathy_chat_get_name (EmpathyChat *chat)
2888 {
2889         EmpathyChatPriv *priv = GET_PRIV (chat);
2890         const gchar *ret;
2891
2892         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2893
2894         ret = priv->name;
2895         if (!ret && priv->remote_contact) {
2896                 ret = empathy_contact_get_name (priv->remote_contact);
2897         }
2898
2899         if (!ret)
2900                 ret = priv->id;
2901
2902         return ret ? ret : _("Conversation");
2903 }
2904
2905 const gchar *
2906 empathy_chat_get_subject (EmpathyChat *chat)
2907 {
2908         EmpathyChatPriv *priv = GET_PRIV (chat);
2909
2910         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2911
2912         return priv->subject;
2913 }
2914
2915 EmpathyContact *
2916 empathy_chat_get_remote_contact (EmpathyChat *chat)
2917 {
2918         EmpathyChatPriv *priv = GET_PRIV (chat);
2919
2920         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2921
2922         return priv->remote_contact;
2923 }
2924
2925 GtkWidget *
2926 empathy_chat_get_contact_menu (EmpathyChat *chat)
2927 {
2928         EmpathyChatPriv *priv = GET_PRIV (chat);
2929         GtkWidget       *menu = NULL;
2930
2931         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2932
2933         if (priv->remote_contact) {
2934                 menu = empathy_contact_menu_new (priv->remote_contact,
2935                                                  EMPATHY_CONTACT_FEATURE_CALL |
2936                                                  EMPATHY_CONTACT_FEATURE_LOG |
2937                                                  EMPATHY_CONTACT_FEATURE_INFO);
2938         }
2939         else if (priv->contact_list_view) {
2940                 EmpathyContactListView *view;
2941
2942                 view = EMPATHY_CONTACT_LIST_VIEW (priv->contact_list_view);
2943                 menu = empathy_contact_list_view_get_contact_menu (view);
2944         }
2945
2946         return menu;
2947 }
2948
2949 void
2950 empathy_chat_clear (EmpathyChat *chat)
2951 {
2952         g_return_if_fail (EMPATHY_IS_CHAT (chat));
2953
2954         empathy_chat_view_clear (chat->view);
2955 }
2956
2957 void
2958 empathy_chat_scroll_down (EmpathyChat *chat)
2959 {
2960         g_return_if_fail (EMPATHY_IS_CHAT (chat));
2961
2962         empathy_chat_view_scroll_down (chat->view);
2963 }
2964
2965 void
2966 empathy_chat_cut (EmpathyChat *chat)
2967 {
2968         GtkTextBuffer *buffer;
2969
2970         g_return_if_fail (EMPATHY_IS_CHAT (chat));
2971
2972         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2973         if (gtk_text_buffer_get_has_selection (buffer)) {
2974                 GtkClipboard *clipboard;
2975
2976                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
2977
2978                 gtk_text_buffer_cut_clipboard (buffer, clipboard, TRUE);
2979         }
2980 }
2981
2982 void
2983 empathy_chat_copy (EmpathyChat *chat)
2984 {
2985         GtkTextBuffer *buffer;
2986
2987         g_return_if_fail (EMPATHY_IS_CHAT (chat));
2988
2989         if (empathy_chat_view_get_has_selection (chat->view)) {
2990                 empathy_chat_view_copy_clipboard (chat->view);
2991                 return;
2992         }
2993
2994         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2995         if (gtk_text_buffer_get_has_selection (buffer)) {
2996                 GtkClipboard *clipboard;
2997
2998                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
2999
3000                 gtk_text_buffer_copy_clipboard (buffer, clipboard);
3001         }
3002 }
3003
3004 void
3005 empathy_chat_paste (EmpathyChat *chat)
3006 {
3007         GtkTextBuffer *buffer;
3008         GtkClipboard  *clipboard;
3009         EmpathyChatPriv *priv;
3010
3011         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3012
3013         priv = GET_PRIV (chat);
3014
3015         if (priv->tp_chat == NULL ||
3016             !GTK_WIDGET_IS_SENSITIVE (chat->input_text_view))
3017                 return;
3018
3019         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3020         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3021
3022         gtk_text_buffer_paste_clipboard (buffer, clipboard, NULL, TRUE);
3023 }
3024
3025 void
3026 empathy_chat_find (EmpathyChat *chat)
3027 {
3028         EmpathyChatPriv *priv;
3029
3030         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3031
3032         priv = GET_PRIV (chat);
3033
3034         empathy_search_bar_show (EMPATHY_SEARCH_BAR (priv->search_bar));
3035 }
3036
3037 void
3038 empathy_chat_correct_word (EmpathyChat  *chat,
3039                           GtkTextIter *start,
3040                           GtkTextIter *end,
3041                           const gchar *new_word)
3042 {
3043         GtkTextBuffer *buffer;
3044
3045         g_return_if_fail (chat != NULL);
3046         g_return_if_fail (new_word != NULL);
3047
3048         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3049
3050         gtk_text_buffer_delete (buffer, start, end);
3051         gtk_text_buffer_insert (buffer, start,
3052                                 new_word,
3053                                 -1);
3054 }
3055
3056 gboolean
3057 empathy_chat_is_room (EmpathyChat *chat)
3058 {
3059         EmpathyChatPriv *priv = GET_PRIV (chat);
3060
3061         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
3062
3063         return (priv->handle_type == TP_HANDLE_TYPE_ROOM);
3064 }
3065
3066 guint
3067 empathy_chat_get_nb_unread_messages (EmpathyChat *self)
3068 {
3069         EmpathyChatPriv *priv = GET_PRIV (self);
3070
3071         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
3072
3073         return priv->unread_messages;
3074 }
3075
3076 /* called when the messages have been read by user */
3077 void
3078 empathy_chat_messages_read (EmpathyChat *self)
3079 {
3080         EmpathyChatPriv *priv = GET_PRIV (self);
3081
3082         g_return_if_fail (EMPATHY_IS_CHAT (self));
3083
3084         /* FIXME: See Bug#610994, See comments about it in EmpathyChatPriv
3085          * definition. If we are still retrieving the backlogs, do not ACK */
3086         if (priv->retrieving_backlogs)
3087                 return;
3088
3089         if (priv->tp_chat != NULL ) {
3090                         empathy_tp_chat_acknowledge_all_messages (priv->tp_chat);
3091         }
3092         priv->unread_messages = 0;
3093 }