]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-chat.c
Merge commit 'staz/dnd'
[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         EmpathyChatPriv *priv;
1248         GtkTextIter     start, end;
1249         gchar          *str;
1250         gboolean        spell_checker = FALSE;
1251
1252         priv = GET_PRIV (chat);
1253
1254         if (gtk_text_buffer_get_char_count (buffer) == 0) {
1255                 chat_composing_stop (chat);
1256         } else {
1257                 chat_composing_start (chat);
1258         }
1259
1260         empathy_conf_get_bool (empathy_conf_get (),
1261                            EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED,
1262                            &spell_checker);
1263
1264         gtk_text_buffer_get_start_iter (buffer, &start);
1265
1266         if (!spell_checker) {
1267                 gtk_text_buffer_get_end_iter (buffer, &end);
1268                 gtk_text_buffer_remove_tag_by_name (buffer, "misspelled", &start, &end);
1269                 return;
1270         }
1271
1272         if (!empathy_spell_supported ()) {
1273                 return;
1274         }
1275
1276         /* NOTE: this is really inefficient, we shouldn't have to
1277            reiterate the whole buffer each time and check each work
1278            every time. */
1279         while (TRUE) {
1280                 gboolean correct = FALSE;
1281
1282                 /* if at start */
1283                 if (gtk_text_iter_is_start (&start)) {
1284                         end = start;
1285
1286                         if (!gtk_text_iter_forward_word_end (&end)) {
1287                                 /* no whole word yet */
1288                                 break;
1289                         }
1290                 } else {
1291                         if (!gtk_text_iter_forward_word_end (&end)) {
1292                                 /* must be the end of the buffer */
1293                                 break;
1294                         }
1295
1296                         start = end;
1297                         gtk_text_iter_backward_word_start (&start);
1298                 }
1299
1300                 str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1301
1302                 /* spell check string if not a command */
1303                 if (str[0] != '/') {
1304                         correct = empathy_spell_check (str);
1305                 } else {
1306                         correct = TRUE;
1307                 }
1308
1309                 if (!correct) {
1310                         gtk_text_buffer_apply_tag_by_name (buffer, "misspelled", &start, &end);
1311                 } else {
1312                         gtk_text_buffer_remove_tag_by_name (buffer, "misspelled", &start, &end);
1313                 }
1314
1315                 g_free (str);
1316
1317                 /* set start iter to the end iters position */
1318                 start = end;
1319         }
1320 }
1321
1322 static gboolean
1323 empathy_isspace_cb (gunichar c,
1324                  gpointer data)
1325 {
1326         return g_unichar_isspace (c);
1327 }
1328
1329 static gboolean
1330 chat_input_key_press_event_cb (GtkWidget   *widget,
1331                                GdkEventKey *event,
1332                                EmpathyChat *chat)
1333 {
1334         EmpathyChatPriv *priv;
1335         GtkAdjustment  *adj;
1336         gdouble         val;
1337         GtkWidget      *text_view_sw;
1338
1339         priv = GET_PRIV (chat);
1340
1341         /* Catch ctrl+up/down so we can traverse messages we sent */
1342         if ((event->state & GDK_CONTROL_MASK) &&
1343             (event->keyval == GDK_Up ||
1344              event->keyval == GDK_Down)) {
1345                 GtkTextBuffer *buffer;
1346                 const gchar   *str;
1347
1348                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1349                 chat_input_history_update (chat, buffer);
1350
1351                 if (event->keyval == GDK_Up) {
1352                         str = chat_input_history_get_next (chat);
1353                 } else {
1354                         str = chat_input_history_get_prev (chat);
1355                 }
1356
1357                 g_signal_handlers_block_by_func (buffer,
1358                                                  chat_input_text_buffer_changed_cb,
1359                                                  chat);
1360                 gtk_text_buffer_set_text (buffer, str ? str : "", -1);
1361                 g_signal_handlers_unblock_by_func (buffer,
1362                                                    chat_input_text_buffer_changed_cb,
1363                                                    chat);
1364
1365                 return TRUE;
1366         }
1367
1368         /* Catch enter but not ctrl/shift-enter */
1369         if (IS_ENTER (event->keyval) &&
1370             !(event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
1371                 GtkTextView *view;
1372
1373                 /* This is to make sure that kinput2 gets the enter. And if
1374                  * it's handled there we shouldn't send on it. This is because
1375                  * kinput2 uses Enter to commit letters. See:
1376                  * http://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=104299
1377                  */
1378
1379                 view = GTK_TEXT_VIEW (chat->input_text_view);
1380                 if (gtk_im_context_filter_keypress (view->im_context, event)) {
1381                         GTK_TEXT_VIEW (chat->input_text_view)->need_im_reset = TRUE;
1382                         return TRUE;
1383                 }
1384
1385                 chat_input_text_view_send (chat);
1386                 return TRUE;
1387         }
1388
1389         text_view_sw = gtk_widget_get_parent (GTK_WIDGET (chat->view));
1390
1391         if (IS_ENTER (event->keyval) &&
1392             (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
1393                 /* Newline for shift/control-enter. */
1394                 return FALSE;
1395         }
1396         if (!(event->state & GDK_CONTROL_MASK) &&
1397             event->keyval == GDK_Page_Up) {
1398                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
1399                 gtk_adjustment_set_value (adj, gtk_adjustment_get_value (adj) - gtk_adjustment_get_page_size (adj));
1400                 return TRUE;
1401         }
1402         if ((event->state & GDK_CONTROL_MASK) != GDK_CONTROL_MASK &&
1403             event->keyval == GDK_Page_Down) {
1404                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
1405                 val = MIN (gtk_adjustment_get_value (adj) + gtk_adjustment_get_page_size (adj),
1406                            gtk_adjustment_get_upper (adj) - gtk_adjustment_get_page_size (adj));
1407                 gtk_adjustment_set_value (adj, val);
1408                 return TRUE;
1409         }
1410         if (event->keyval == GDK_Escape) {
1411                 empathy_search_bar_hide (EMPATHY_SEARCH_BAR (priv->search_bar));
1412         }
1413         if (!(event->state & (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) &&
1414             event->keyval == GDK_Tab) {
1415                 GtkTextBuffer *buffer;
1416                 GtkTextIter    start, current;
1417                 gchar         *nick, *completed;
1418                 GList         *list, *completed_list;
1419                 gboolean       is_start_of_buffer;
1420
1421                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (EMPATHY_CHAT (chat)->input_text_view));
1422                 gtk_text_buffer_get_iter_at_mark (buffer, &current, gtk_text_buffer_get_insert (buffer));
1423
1424                 /* Get the start of the nick to complete. */
1425                 gtk_text_buffer_get_iter_at_mark (buffer, &start, gtk_text_buffer_get_insert (buffer));
1426                 if (gtk_text_iter_backward_find_char (&start, &empathy_isspace_cb, NULL, NULL)) {
1427                         gtk_text_iter_set_offset (&start, gtk_text_iter_get_offset (&start) + 1);
1428                 }
1429                 is_start_of_buffer = gtk_text_iter_is_start (&start);
1430
1431                 list = empathy_contact_list_get_members (EMPATHY_CONTACT_LIST (priv->tp_chat));
1432                 g_completion_add_items (priv->completion, list);
1433
1434                 nick = gtk_text_buffer_get_text (buffer, &start, &current, FALSE);
1435                 completed_list = g_completion_complete (priv->completion,
1436                                                         nick,
1437                                                         &completed);
1438
1439                 g_free (nick);
1440
1441                 if (completed) {
1442                         guint        len;
1443                         const gchar *text;
1444                         gchar       *complete_char = NULL;
1445                         GString     *message = NULL;
1446                         GList       *l;
1447
1448                         gtk_text_buffer_delete (buffer, &start, &current);
1449
1450                         len = g_list_length (completed_list);
1451
1452                         if (len == 1) {
1453                                 /* If we only have one hit, use that text
1454                                  * instead of the text in completed since the
1455                                  * completed text will use the typed string
1456                                  * which might be cased all wrong.
1457                                  * Fixes #120876
1458                                  * */
1459                                 text = empathy_contact_get_name (completed_list->data);
1460                         } else {
1461                                 text = completed;
1462
1463                                 /* Print all hits to the scrollback view, so the
1464                                  * user knows what possibilities he has.
1465                                  * Fixes #599779
1466                                  * */
1467                                  message = g_string_new ("");
1468                                  for (l = completed_list; l != NULL; l = l->next) {
1469                                         g_string_append (message, empathy_contact_get_name (l->data));
1470                                         g_string_append (message, " - ");
1471                                  }
1472                                  empathy_chat_view_append_event (chat->view, message->str);
1473                                  g_string_free (message, TRUE);
1474                         }
1475
1476                         gtk_text_buffer_insert_at_cursor (buffer, text, strlen (text));
1477
1478                         if (len == 1 && is_start_of_buffer &&
1479                             empathy_conf_get_string (empathy_conf_get (),
1480                                                      EMPATHY_PREFS_CHAT_NICK_COMPLETION_CHAR,
1481                                                      &complete_char) &&
1482                             complete_char != NULL) {
1483                                 gtk_text_buffer_insert_at_cursor (buffer,
1484                                                                   complete_char,
1485                                                                   strlen (complete_char));
1486                                 gtk_text_buffer_insert_at_cursor (buffer, " ", 1);
1487                                 g_free (complete_char);
1488                         }
1489
1490                         g_free (completed);
1491                 }
1492
1493                 g_completion_clear_items (priv->completion);
1494
1495                 g_list_foreach (list, (GFunc) g_object_unref, NULL);
1496                 g_list_free (list);
1497
1498                 return TRUE;
1499         }
1500
1501         return FALSE;
1502 }
1503
1504 static gboolean
1505 chat_text_view_focus_in_event_cb (GtkWidget  *widget,
1506                                   GdkEvent   *event,
1507                                   EmpathyChat *chat)
1508 {
1509         gtk_widget_grab_focus (chat->input_text_view);
1510
1511         return TRUE;
1512 }
1513
1514 static gboolean
1515 chat_input_set_size_request_idle (gpointer sw)
1516 {
1517         gtk_widget_set_size_request (sw, -1, MAX_INPUT_HEIGHT);
1518
1519         return FALSE;
1520 }
1521
1522 static void
1523 chat_input_size_request_cb (GtkWidget      *widget,
1524                             GtkRequisition *requisition,
1525                             EmpathyChat    *chat)
1526 {
1527         EmpathyChatPriv *priv = GET_PRIV (chat);
1528         GtkWidget       *sw;
1529
1530         sw = gtk_widget_get_parent (widget);
1531         if (requisition->height >= MAX_INPUT_HEIGHT && !priv->has_input_vscroll) {
1532                 g_idle_add (chat_input_set_size_request_idle, sw);
1533                 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw),
1534                                                 GTK_POLICY_NEVER,
1535                                                 GTK_POLICY_ALWAYS);
1536                 priv->has_input_vscroll = TRUE;
1537         }
1538
1539         if (requisition->height < MAX_INPUT_HEIGHT && priv->has_input_vscroll) {
1540                 gtk_widget_set_size_request (sw, -1, -1);
1541                 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw),
1542                                                 GTK_POLICY_NEVER,
1543                                                 GTK_POLICY_NEVER);
1544                 priv->has_input_vscroll = FALSE;
1545         }
1546 }
1547
1548 static void
1549 chat_input_realize_cb (GtkWidget   *widget,
1550                        EmpathyChat *chat)
1551 {
1552         DEBUG ("Setting focus to the input text view");
1553         if (gtk_widget_is_sensitive (widget)) {
1554                 gtk_widget_grab_focus (widget);
1555         }
1556 }
1557
1558 static void
1559 chat_insert_smiley_activate_cb (EmpathySmileyManager *manager,
1560                                 EmpathySmiley        *smiley,
1561                                 gpointer              user_data)
1562 {
1563         EmpathyChat   *chat = EMPATHY_CHAT (user_data);
1564         GtkTextBuffer *buffer;
1565         GtkTextIter    iter;
1566
1567         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1568
1569         gtk_text_buffer_get_end_iter (buffer, &iter);
1570         gtk_text_buffer_insert (buffer, &iter, smiley->str, -1);
1571
1572         gtk_text_buffer_get_end_iter (buffer, &iter);
1573         gtk_text_buffer_insert (buffer, &iter, " ", -1);
1574 }
1575
1576 typedef struct {
1577         EmpathyChat  *chat;
1578         gchar       *word;
1579
1580         GtkTextIter  start;
1581         GtkTextIter  end;
1582 } EmpathyChatSpell;
1583
1584 static EmpathyChatSpell *
1585 chat_spell_new (EmpathyChat  *chat,
1586                 const gchar *word,
1587                 GtkTextIter  start,
1588                 GtkTextIter  end)
1589 {
1590         EmpathyChatSpell *chat_spell;
1591
1592         chat_spell = g_slice_new0 (EmpathyChatSpell);
1593
1594         chat_spell->chat = g_object_ref (chat);
1595         chat_spell->word = g_strdup (word);
1596         chat_spell->start = start;
1597         chat_spell->end = end;
1598
1599         return chat_spell;
1600 }
1601
1602 static void
1603 chat_spell_free (EmpathyChatSpell *chat_spell)
1604 {
1605         g_object_unref (chat_spell->chat);
1606         g_free (chat_spell->word);
1607         g_slice_free (EmpathyChatSpell, chat_spell);
1608 }
1609
1610 static void
1611 chat_spelling_menu_activate_cb (GtkMenuItem     *menu_item,
1612                                                 EmpathyChatSpell *chat_spell)
1613 {
1614     empathy_chat_correct_word (chat_spell->chat,
1615                                &(chat_spell->start),
1616                                &(chat_spell->end),
1617                                gtk_menu_item_get_label (menu_item));
1618 }
1619
1620 static GtkWidget *
1621 chat_spelling_build_menu (EmpathyChatSpell *chat_spell)
1622 {
1623     GtkWidget *menu, *menu_item;
1624     GList     *suggestions, *l;
1625
1626     menu = gtk_menu_new ();
1627     suggestions = empathy_spell_get_suggestions (chat_spell->word);
1628     if (suggestions == NULL) {
1629         menu_item = gtk_menu_item_new_with_label (_("(No Suggestions)"));
1630         gtk_widget_set_sensitive (menu_item, FALSE);
1631         gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
1632     } else {
1633         for (l = suggestions; l; l = l->next) {
1634             menu_item = gtk_menu_item_new_with_label (l->data);
1635             g_signal_connect (G_OBJECT (menu_item),
1636                           "activate",
1637                           G_CALLBACK (chat_spelling_menu_activate_cb),
1638                           chat_spell);
1639             gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
1640         }
1641     }
1642     empathy_spell_free_suggestions (suggestions);
1643
1644     gtk_widget_show_all (menu);
1645
1646     return menu;
1647 }
1648
1649 static void
1650 chat_text_send_cb (GtkMenuItem *menuitem,
1651                    EmpathyChat *chat)
1652 {
1653         chat_input_text_view_send (chat);
1654 }
1655
1656 static void
1657 chat_input_populate_popup_cb (GtkTextView *view,
1658                               GtkMenu     *menu,
1659                               EmpathyChat *chat)
1660 {
1661         EmpathyChatPriv      *priv;
1662         GtkTextBuffer        *buffer;
1663         GtkTextTagTable      *table;
1664         GtkTextTag           *tag;
1665         gint                  x, y;
1666         GtkTextIter           iter, start, end;
1667         GtkWidget            *item;
1668         gchar                *str = NULL;
1669         EmpathyChatSpell     *chat_spell;
1670         GtkWidget            *spell_menu;
1671         EmpathySmileyManager *smiley_manager;
1672         GtkWidget            *smiley_menu;
1673         GtkWidget            *image;
1674
1675         priv = GET_PRIV (chat);
1676         buffer = gtk_text_view_get_buffer (view);
1677
1678         /* Add the emoticon menu. */
1679         item = gtk_separator_menu_item_new ();
1680         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1681         gtk_widget_show (item);
1682
1683         item = gtk_image_menu_item_new_with_mnemonic (_("Insert Smiley"));
1684         image = gtk_image_new_from_icon_name ("face-smile",
1685                                               GTK_ICON_SIZE_MENU);
1686         gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
1687         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1688         gtk_widget_show (item);
1689
1690         smiley_manager = empathy_smiley_manager_dup_singleton ();
1691         smiley_menu = empathy_smiley_menu_new (smiley_manager,
1692                                                chat_insert_smiley_activate_cb,
1693                                                chat);
1694         gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), smiley_menu);
1695         g_object_unref (smiley_manager);
1696
1697         /* Add the Send menu item. */
1698         gtk_text_buffer_get_bounds (buffer, &start, &end);
1699         str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1700         if (!EMP_STR_EMPTY (str)) {
1701                 item = gtk_menu_item_new_with_mnemonic (_("_Send"));
1702                 g_signal_connect (G_OBJECT (item), "activate",
1703                                   G_CALLBACK (chat_text_send_cb), chat);
1704                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1705                 gtk_widget_show (item);
1706         }
1707         str = NULL;
1708
1709         /* Add the spell check menu item. */
1710         table = gtk_text_buffer_get_tag_table (buffer);
1711         tag = gtk_text_tag_table_lookup (table, "misspelled");
1712         gtk_widget_get_pointer (GTK_WIDGET (view), &x, &y);
1713         gtk_text_view_window_to_buffer_coords (GTK_TEXT_VIEW (view),
1714                                                GTK_TEXT_WINDOW_WIDGET,
1715                                                x, y,
1716                                                &x, &y);
1717         gtk_text_view_get_iter_at_location (GTK_TEXT_VIEW (view), &iter, x, y);
1718         start = end = iter;
1719         if (gtk_text_iter_backward_to_tag_toggle (&start, tag) &&
1720             gtk_text_iter_forward_to_tag_toggle (&end, tag)) {
1721
1722                 str = gtk_text_buffer_get_text (buffer,
1723                                                 &start, &end, FALSE);
1724         }
1725         if (!EMP_STR_EMPTY (str)) {
1726                 chat_spell = chat_spell_new (chat, str, start, end);
1727                 g_object_set_data_full (G_OBJECT (menu),
1728                                         "chat_spell", chat_spell,
1729                                         (GDestroyNotify) chat_spell_free);
1730
1731                 item = gtk_separator_menu_item_new ();
1732                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1733                 gtk_widget_show (item);
1734
1735                 item = gtk_image_menu_item_new_with_mnemonic (_("_Spelling Suggestions"));
1736                 image = gtk_image_new_from_icon_name (GTK_STOCK_SPELL_CHECK,
1737                                                       GTK_ICON_SIZE_MENU);
1738                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
1739
1740                 spell_menu = chat_spelling_build_menu (chat_spell);
1741                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), spell_menu);
1742
1743                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1744                 gtk_widget_show (item);
1745         }
1746 }
1747
1748
1749 #ifdef ENABLE_TPL
1750 static gboolean
1751 chat_log_filter (TplLogEntry *log,
1752                  gpointer user_data)
1753 #else
1754 static gboolean
1755 chat_log_filter (EmpathyMessage *message,
1756                  gpointer user_data)
1757 #endif /* ENABLE_TPL */
1758 {
1759         EmpathyChat *chat = user_data;
1760 #ifdef ENABLE_TPL
1761         EmpathyMessage *message;
1762 #endif /* ENABLE_TPL */
1763         EmpathyChatPriv *priv = GET_PRIV (chat);
1764         const GList *pending;
1765
1766 #ifdef ENABLE_TPL
1767         g_return_val_if_fail (TPL_IS_LOG_ENTRY (log), FALSE);
1768 #else
1769         g_return_val_if_fail (EMPATHY_IS_MESSAGE (message), FALSE);
1770 #endif /* ENABLE_TPL */
1771         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
1772
1773         pending = empathy_tp_chat_get_pending_messages (priv->tp_chat);
1774 #ifdef ENABLE_TPL
1775         message = empathy_message_from_tpl_log_entry (log);
1776 #endif /* ENABLE_TPL */
1777
1778         for (; pending; pending = g_list_next (pending)) {
1779                 if (empathy_message_equal (message, pending->data)) {
1780                         return FALSE;
1781                 }
1782         }
1783 #ifdef ENABLE_TPL
1784         g_object_unref (message);
1785 #endif
1786         return TRUE;
1787 }
1788
1789
1790 static void
1791 show_pending_messages (EmpathyChat *chat) {
1792         EmpathyChatPriv *priv = GET_PRIV (chat);
1793         const GList *messages, *l;
1794
1795         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1796
1797         if (chat->view == NULL || priv->tp_chat == NULL)
1798                 return;
1799
1800         if (!priv->can_show_pending)
1801                 return;
1802
1803         messages = empathy_tp_chat_get_pending_messages (priv->tp_chat);
1804
1805         for (l = messages; l != NULL ; l = g_list_next (l)) {
1806                 EmpathyMessage *message = EMPATHY_MESSAGE (l->data);
1807                 chat_message_received (chat, message);
1808         }
1809 }
1810
1811
1812 #ifdef ENABLE_TPL
1813 static void
1814 got_filtered_messages_cb (GObject *manager,
1815                 GAsyncResult *result,
1816                 gpointer user_data)
1817 {
1818         GList *l;
1819         GList *messages;
1820         EmpathyChat *chat = EMPATHY_CHAT (user_data);
1821         EmpathyChatPriv *priv = GET_PRIV (chat);
1822         GError *error = NULL;
1823
1824         messages = tpl_log_manager_get_filtered_messages_async_finish (result, &error);
1825
1826         if (error != NULL) {
1827                 DEBUG ("%s. Aborting.", error->message);
1828                 empathy_chat_view_append_event (chat->view,
1829                         _("Failed to retrieve recent logs"));
1830                 g_error_free (error);
1831                 goto out;
1832         }
1833
1834         for (l = messages; l; l = g_list_next (l)) {
1835                 EmpathyMessage *message;
1836                 g_assert (TPL_IS_LOG_ENTRY (l->data));
1837
1838                 message = empathy_message_from_tpl_log_entry (l->data);
1839                 g_object_unref (l->data);
1840
1841                 empathy_chat_view_append_message (chat->view, message);
1842                 g_object_unref (message);
1843         }
1844         g_list_free (messages);
1845
1846 out:
1847         /* in case of TPL error, skip backlog and show pending messages */
1848         priv->can_show_pending = TRUE;
1849         show_pending_messages (chat);
1850
1851         /* FIXME: See Bug#610994, we are forcing the ACK of the queue. See comments
1852          * about it in EmpathyChatPriv definition */
1853         priv->retrieving_backlogs = FALSE;
1854         empathy_chat_messages_read (chat);
1855
1856         /* Turn back on scrolling */
1857         empathy_chat_view_scroll (chat->view, TRUE);
1858 }
1859 #endif /* ENABLE_TPL */
1860
1861
1862 static void
1863 chat_add_logs (EmpathyChat *chat)
1864 {
1865         EmpathyChatPriv *priv = GET_PRIV (chat);
1866         gboolean         is_chatroom;
1867 #ifndef ENABLE_TPL
1868         GList           *messages, *l;
1869 #endif /* ENABLE_TPL */
1870
1871         if (!priv->id) {
1872                 return;
1873         }
1874
1875         /* Turn off scrolling temporarily */
1876         empathy_chat_view_scroll (chat->view, FALSE);
1877
1878         /* Add messages from last conversation */
1879         is_chatroom = priv->handle_type == TP_HANDLE_TYPE_ROOM;
1880
1881 #ifndef ENABLE_TPL
1882         messages = empathy_log_manager_get_filtered_messages (priv->log_manager,
1883                                                               priv->account,
1884                                                               priv->id,
1885                                                               is_chatroom,
1886                                                               5,
1887                                                               chat_log_filter,
1888                                                               chat);
1889
1890         for (l = messages; l; l = g_list_next (l)) {
1891                 empathy_chat_view_append_message (chat->view, l->data);
1892                 g_object_unref (l->data);
1893         }
1894
1895         g_list_free (messages);
1896
1897         /* Turn back on scrolling */
1898         empathy_chat_view_scroll (chat->view, TRUE);
1899 #else
1900         priv->retrieving_backlogs = TRUE;
1901         tpl_log_manager_get_filtered_messages_async (priv->log_manager,
1902                                                               priv->account,
1903                                                               priv->id,
1904                                                               is_chatroom,
1905                                                               5,
1906                                                               chat_log_filter,
1907                                                               chat,
1908                                                               got_filtered_messages_cb,
1909                                                               (gpointer) chat);
1910 #endif /* ENABLE_TPL */
1911 }
1912
1913 static gint
1914 chat_contacts_completion_func (const gchar *s1,
1915                                const gchar *s2,
1916                                gsize        n)
1917 {
1918         gchar *tmp, *nick1, *nick2;
1919         gint   ret;
1920
1921         if (s1 == s2) {
1922                 return 0;
1923         }
1924         if (!s1 || !s2) {
1925                 return s1 ? -1 : +1;
1926         }
1927
1928         tmp = g_utf8_normalize (s1, -1, G_NORMALIZE_DEFAULT);
1929         nick1 = g_utf8_casefold (tmp, -1);
1930         g_free (tmp);
1931
1932         tmp = g_utf8_normalize (s2, -1, G_NORMALIZE_DEFAULT);
1933         nick2 = g_utf8_casefold (tmp, -1);
1934         g_free (tmp);
1935
1936         ret = strncmp (nick1, nick2, n);
1937
1938         g_free (nick1);
1939         g_free (nick2);
1940
1941         return ret;
1942 }
1943
1944 static gchar *
1945 build_part_message (guint           reason,
1946                     const gchar    *name,
1947                     EmpathyContact *actor,
1948                     const gchar    *message)
1949 {
1950         GString *s = g_string_new ("");
1951         const gchar *actor_name = NULL;
1952
1953         if (actor != NULL) {
1954                 actor_name = empathy_contact_get_name (actor);
1955         }
1956
1957         /* Having an actor only really makes sense for a few actions... */
1958         switch (reason) {
1959         case TP_CHANNEL_GROUP_CHANGE_REASON_OFFLINE:
1960                 g_string_append_printf (s, _("%s has disconnected"), name);
1961                 break;
1962         case TP_CHANNEL_GROUP_CHANGE_REASON_KICKED:
1963                 if (actor_name != NULL) {
1964                         /* translators: reverse the order of these arguments
1965                          * if the kicked should come before the kicker in your locale.
1966                          */
1967                         g_string_append_printf (s, _("%1$s was kicked by %2$s"),
1968                                 name, actor_name);
1969                 } else {
1970                         g_string_append_printf (s, _("%s was kicked"), name);
1971                 }
1972                 break;
1973         case TP_CHANNEL_GROUP_CHANGE_REASON_BANNED:
1974                 if (actor_name != NULL) {
1975                         /* translators: reverse the order of these arguments
1976                          * if the banned should come before the banner in your locale.
1977                          */
1978                         g_string_append_printf (s, _("%1$s was banned by %2$s"),
1979                                 name, actor_name);
1980                 } else {
1981                         g_string_append_printf (s, _("%s was banned"), name);
1982                 }
1983                 break;
1984         default:
1985                 g_string_append_printf (s, _("%s has left the room"), name);
1986         }
1987
1988         if (!EMP_STR_EMPTY (message)) {
1989                 /* Note to translators: this string is appended to
1990                  * notifications like "foo has left the room", with the message
1991                  * given by the user living the room. If this poses a problem,
1992                  * please let us know. :-)
1993                  */
1994                 g_string_append_printf (s, _(" (%s)"), message);
1995         }
1996
1997         return g_string_free (s, FALSE);
1998 }
1999
2000 static void
2001 chat_members_changed_cb (EmpathyTpChat  *tp_chat,
2002                          EmpathyContact *contact,
2003                          EmpathyContact *actor,
2004                          guint           reason,
2005                          gchar          *message,
2006                          gboolean        is_member,
2007                          EmpathyChat    *chat)
2008 {
2009         EmpathyChatPriv *priv = GET_PRIV (chat);
2010         const gchar *name = empathy_contact_get_name (contact);
2011         gchar *str;
2012
2013         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED != reason);
2014
2015         if (priv->block_events_timeout_id != 0)
2016                 return;
2017
2018         if (is_member) {
2019                 str = g_strdup_printf (_("%s has joined the room"),
2020                                        name);
2021         } else {
2022                 str = build_part_message (reason, name, actor, message);
2023         }
2024
2025         empathy_chat_view_append_event (chat->view, str);
2026         g_free (str);
2027 }
2028
2029 static void
2030 chat_member_renamed_cb (EmpathyTpChat  *tp_chat,
2031                          EmpathyContact *old_contact,
2032                          EmpathyContact *new_contact,
2033                          guint           reason,
2034                          gchar          *message,
2035                          EmpathyChat    *chat)
2036 {
2037         EmpathyChatPriv *priv = GET_PRIV (chat);
2038
2039         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED == reason);
2040
2041         if (priv->block_events_timeout_id == 0) {
2042                 gchar *str;
2043
2044                 str = g_strdup_printf (_("%s is now known as %s"),
2045                                        empathy_contact_get_name (old_contact),
2046                                        empathy_contact_get_name (new_contact));
2047                 empathy_chat_view_append_event (chat->view, str);
2048                 g_free (str);
2049         }
2050
2051 }
2052
2053 static gboolean
2054 chat_reset_size_request (gpointer widget)
2055 {
2056         gtk_widget_set_size_request (widget, -1, -1);
2057
2058         return FALSE;
2059 }
2060
2061 static void
2062 chat_update_contacts_visibility (EmpathyChat *chat,
2063                          gboolean show)
2064 {
2065         EmpathyChatPriv *priv = GET_PRIV (chat);
2066         GtkAllocation allocation;
2067
2068         if (!priv->scrolled_window_contacts) {
2069                 return;
2070         }
2071
2072         if (priv->remote_contact != NULL) {
2073                 show = FALSE;
2074         }
2075
2076         if (show && priv->contact_list_view == NULL) {
2077                 EmpathyContactListStore *store;
2078                 gint                     min_width;
2079
2080                 /* We are adding the contact list to the chat, we don't want the
2081                  * chat view to become too small. If the chat view is already
2082                  * smaller than 250 make sure that size won't change. If the
2083                  * chat view is bigger the contact list will take some space on
2084                  * it but we make sure the chat view don't become smaller than
2085                  * 250. Relax the size request once the resize is done */
2086                 gtk_widget_get_allocation (priv->vbox_left, &allocation);
2087                 min_width = MIN (allocation.width, 250);
2088                 gtk_widget_set_size_request (priv->vbox_left, min_width, -1);
2089                 g_idle_add (chat_reset_size_request, priv->vbox_left);
2090
2091                 if (priv->contacts_width > 0) {
2092                         gtk_paned_set_position (GTK_PANED (priv->hpaned),
2093                                                 priv->contacts_width);
2094                 }
2095
2096                 store = empathy_contact_list_store_new (EMPATHY_CONTACT_LIST (priv->tp_chat));
2097                 priv->contact_list_view = GTK_WIDGET (empathy_contact_list_view_new (store,
2098                         EMPATHY_CONTACT_LIST_FEATURE_CONTACT_TOOLTIP,
2099                         EMPATHY_CONTACT_FEATURE_CHAT |
2100                         EMPATHY_CONTACT_FEATURE_CALL |
2101                         EMPATHY_CONTACT_FEATURE_LOG |
2102                         EMPATHY_CONTACT_FEATURE_INFO));
2103                 gtk_container_add (GTK_CONTAINER (priv->scrolled_window_contacts),
2104                                    priv->contact_list_view);
2105                 gtk_widget_show (priv->contact_list_view);
2106                 gtk_widget_show (priv->scrolled_window_contacts);
2107                 g_object_unref (store);
2108         } else if (!show) {
2109                 priv->contacts_width = gtk_paned_get_position (GTK_PANED (priv->hpaned));
2110                 gtk_widget_hide (priv->scrolled_window_contacts);
2111                 if (priv->contact_list_view != NULL) {
2112                         gtk_widget_destroy (priv->contact_list_view);
2113                         priv->contact_list_view = NULL;
2114                 }
2115         }
2116 }
2117
2118 void
2119 empathy_chat_set_show_contacts (EmpathyChat *chat,
2120                                 gboolean     show)
2121 {
2122         EmpathyChatPriv *priv = GET_PRIV (chat);
2123
2124         priv->show_contacts = show;
2125
2126         chat_update_contacts_visibility (chat, show);
2127
2128         g_object_notify (G_OBJECT (chat), "show-contacts");
2129 }
2130
2131 static void
2132 chat_remote_contact_changed_cb (EmpathyChat *chat)
2133 {
2134         EmpathyChatPriv *priv = GET_PRIV (chat);
2135
2136         if (priv->remote_contact != NULL) {
2137                 g_object_unref (priv->remote_contact);
2138                 priv->remote_contact = NULL;
2139         }
2140
2141         g_free (priv->id);
2142
2143         priv->id = g_strdup (empathy_tp_chat_get_id (priv->tp_chat));
2144         priv->remote_contact = empathy_tp_chat_get_remote_contact (priv->tp_chat);
2145         if (priv->remote_contact != NULL) {
2146                 g_object_ref (priv->remote_contact);
2147                 priv->handle_type = TP_HANDLE_TYPE_CONTACT;
2148         }
2149         else if (priv->tp_chat != NULL) {
2150                 TpChannel *channel;
2151
2152                 channel = empathy_tp_chat_get_channel (priv->tp_chat);
2153                 g_object_get (channel, "handle-type", &priv->handle_type, NULL);
2154         }
2155
2156         chat_update_contacts_visibility (chat, priv->show_contacts);
2157
2158         g_object_notify (G_OBJECT (chat), "remote-contact");
2159         g_object_notify (G_OBJECT (chat), "id");
2160 }
2161
2162 static void
2163 chat_destroy_cb (EmpathyTpChat *tp_chat,
2164                  EmpathyChat   *chat)
2165 {
2166         EmpathyChatPriv *priv;
2167
2168         priv = GET_PRIV (chat);
2169
2170         if (!priv->tp_chat) {
2171                 return;
2172         }
2173
2174         chat_composing_remove_timeout (chat);
2175         g_object_unref (priv->tp_chat);
2176         priv->tp_chat = NULL;
2177         g_object_notify (G_OBJECT (chat), "tp-chat");
2178
2179         empathy_chat_view_append_event (chat->view, _("Disconnected"));
2180         gtk_widget_set_sensitive (chat->input_text_view, FALSE);
2181
2182         chat_update_contacts_visibility (chat, FALSE);
2183 }
2184
2185 static gboolean
2186 chat_hpaned_pos_changed_cb (GtkWidget* hpaned, gpointer user_data)
2187 {
2188         gint hpaned_pos;
2189         hpaned_pos = gtk_paned_get_position (GTK_PANED(hpaned));
2190         empathy_conf_set_int (empathy_conf_get (),
2191                               EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS,
2192                               hpaned_pos);
2193         return TRUE;
2194 }
2195
2196 static void
2197 chat_create_ui (EmpathyChat *chat)
2198 {
2199         EmpathyChatPriv *priv = GET_PRIV (chat);
2200         GtkBuilder      *gui;
2201         GList           *list = NULL;
2202         gchar           *filename;
2203         GtkTextBuffer   *buffer;
2204         gint              paned_pos;
2205
2206         filename = empathy_file_lookup ("empathy-chat.ui",
2207                                         "libempathy-gtk");
2208         gui = empathy_builder_get_file (filename,
2209                                         "chat_widget", &priv->widget,
2210                                         "hpaned", &priv->hpaned,
2211                                         "vbox_left", &priv->vbox_left,
2212                                         "scrolled_window_chat", &priv->scrolled_window_chat,
2213                                         "scrolled_window_input", &priv->scrolled_window_input,
2214                                         "hbox_topic", &priv->hbox_topic,
2215                                         "label_topic", &priv->label_topic,
2216                                         "scrolled_window_contacts", &priv->scrolled_window_contacts,
2217                                         "info_bar_vbox", &priv->info_bar_vbox,
2218                                         NULL);
2219         g_free (filename);
2220
2221         /* Add message view. */
2222         chat->view = empathy_theme_manager_create_view (empathy_theme_manager_get ());
2223         /* If this is a GtkTextView, it's set as a drag destination for text/plain
2224            and other types, even though it's non-editable and doesn't accept any
2225            drags.  This steals drag motion for anything inside the scrollbars,
2226            making drag destinations on chat windows far less useful.
2227          */
2228         gtk_drag_dest_unset (GTK_WIDGET (chat->view));
2229         g_signal_connect (chat->view, "focus_in_event",
2230                           G_CALLBACK (chat_text_view_focus_in_event_cb),
2231                           chat);
2232         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_chat),
2233                            GTK_WIDGET (chat->view));
2234         gtk_widget_show (GTK_WIDGET (chat->view));
2235
2236         /* Add input GtkTextView */
2237         chat->input_text_view = g_object_new (GTK_TYPE_TEXT_VIEW,
2238                                               "pixels-above-lines", 2,
2239                                               "pixels-below-lines", 2,
2240                                               "pixels-inside-wrap", 1,
2241                                               "right-margin", 2,
2242                                               "left-margin", 2,
2243                                               "wrap-mode", GTK_WRAP_WORD_CHAR,
2244                                               NULL);
2245         g_signal_connect (chat->input_text_view, "key-press-event",
2246                           G_CALLBACK (chat_input_key_press_event_cb),
2247                           chat);
2248         g_signal_connect (chat->input_text_view, "size-request",
2249                           G_CALLBACK (chat_input_size_request_cb),
2250                           chat);
2251         g_signal_connect (chat->input_text_view, "realize",
2252                           G_CALLBACK (chat_input_realize_cb),
2253                           chat);
2254         g_signal_connect (chat->input_text_view, "populate-popup",
2255                           G_CALLBACK (chat_input_populate_popup_cb),
2256                           chat);
2257         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2258         g_signal_connect (buffer, "changed",
2259                           G_CALLBACK (chat_input_text_buffer_changed_cb),
2260                           chat);
2261         gtk_text_buffer_create_tag (buffer, "misspelled",
2262                                     "underline", PANGO_UNDERLINE_ERROR,
2263                                     NULL);
2264         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_input),
2265                            chat->input_text_view);
2266         gtk_widget_show (chat->input_text_view);
2267
2268         /* Add the (invisible) search bar */
2269         priv->search_bar = empathy_search_bar_new (chat->view);
2270         gtk_box_pack_start (GTK_BOX(priv->vbox_left),
2271                             priv->search_bar,
2272                             FALSE, FALSE, 0);
2273         gtk_box_reorder_child (GTK_BOX(priv->vbox_left), priv->search_bar, 1);
2274
2275         /* Initialy hide the topic, will be shown if not empty */
2276         gtk_widget_hide (priv->hbox_topic);
2277
2278         g_signal_connect (priv->hpaned, "notify::position",
2279                           G_CALLBACK (chat_hpaned_pos_changed_cb),
2280                           NULL);
2281
2282         /* Load the paned position */
2283         if (empathy_conf_get_int (empathy_conf_get (),
2284                                  EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS,
2285                                  &paned_pos)
2286                 && paned_pos)
2287                 gtk_paned_set_position (GTK_PANED(priv->hpaned), paned_pos);
2288
2289         /* Set widget focus order */
2290         list = g_list_append (NULL, priv->search_bar);
2291         list = g_list_append (list, priv->scrolled_window_input);
2292         gtk_container_set_focus_chain (GTK_CONTAINER (priv->vbox_left), list);
2293         g_list_free (list);
2294
2295         list = g_list_append (NULL, priv->vbox_left);
2296         list = g_list_append (list, priv->scrolled_window_contacts);
2297         gtk_container_set_focus_chain (GTK_CONTAINER (priv->hpaned), list);
2298         g_list_free (list);
2299
2300         list = g_list_append (NULL, priv->hpaned);
2301         list = g_list_append (list, priv->hbox_topic);
2302         gtk_container_set_focus_chain (GTK_CONTAINER (priv->widget), list);
2303         g_list_free (list);
2304
2305         /* Add the main widget in the chat widget */
2306         gtk_container_add (GTK_CONTAINER (chat), priv->widget);
2307         g_object_unref (gui);
2308 }
2309
2310 static void
2311 chat_size_request (GtkWidget      *widget,
2312                    GtkRequisition *requisition)
2313 {
2314   GtkBin *bin = GTK_BIN (widget);
2315   GtkWidget *child;
2316
2317   requisition->width = gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2;
2318   requisition->height = gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2;
2319
2320   child = gtk_bin_get_child (bin);
2321
2322   if (child && gtk_widget_get_visible (child))
2323     {
2324       GtkRequisition child_requisition;
2325
2326       gtk_widget_size_request (child, &child_requisition);
2327
2328       requisition->width += child_requisition.width;
2329       requisition->height += child_requisition.height;
2330     }
2331 }
2332
2333 static void
2334 chat_size_allocate (GtkWidget     *widget,
2335                     GtkAllocation *allocation)
2336 {
2337   GtkBin *bin = GTK_BIN (widget);
2338   GtkAllocation child_allocation;
2339   GtkWidget *child;
2340
2341   gtk_widget_set_allocation (widget, allocation);
2342
2343   child = gtk_bin_get_child (bin);
2344
2345   if (child && gtk_widget_get_visible (child))
2346     {
2347       child_allocation.x = allocation->x + gtk_container_get_border_width (GTK_CONTAINER (widget));
2348       child_allocation.y = allocation->y + gtk_container_get_border_width (GTK_CONTAINER (widget));
2349       child_allocation.width = MAX (allocation->width - gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2, 0);
2350       child_allocation.height = MAX (allocation->height - gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2, 0);
2351
2352       gtk_widget_size_allocate (child, &child_allocation);
2353     }
2354 }
2355
2356 static void
2357 chat_finalize (GObject *object)
2358 {
2359         EmpathyChat     *chat;
2360         EmpathyChatPriv *priv;
2361
2362         chat = EMPATHY_CHAT (object);
2363         priv = GET_PRIV (chat);
2364
2365         DEBUG ("Finalized: %p", object);
2366
2367         g_list_foreach (priv->input_history, (GFunc) chat_input_history_entry_free, NULL);
2368         g_list_free (priv->input_history);
2369
2370         g_list_foreach (priv->compositors, (GFunc) g_object_unref, NULL);
2371         g_list_free (priv->compositors);
2372
2373         chat_composing_remove_timeout (chat);
2374
2375         g_object_unref (priv->account_manager);
2376         g_object_unref (priv->log_manager);
2377
2378         if (priv->tp_chat) {
2379                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2380                         chat_destroy_cb, chat);
2381                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2382                         chat_message_received_cb, chat);
2383                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2384                         chat_send_error_cb, chat);
2385                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2386                         chat_state_changed_cb, chat);
2387                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2388                         chat_property_changed_cb, chat);
2389                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2390                         chat_members_changed_cb, chat);
2391                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2392                         chat_remote_contact_changed_cb, chat);
2393                 empathy_tp_chat_leave (priv->tp_chat);
2394                 g_object_unref (priv->tp_chat);
2395         }
2396         if (priv->account) {
2397                 g_object_unref (priv->account);
2398         }
2399         if (priv->remote_contact) {
2400                 g_object_unref (priv->remote_contact);
2401         }
2402
2403         if (priv->block_events_timeout_id) {
2404                 g_source_remove (priv->block_events_timeout_id);
2405         }
2406
2407         g_free (priv->id);
2408         g_free (priv->name);
2409         g_free (priv->subject);
2410         g_completion_free (priv->completion);
2411
2412         G_OBJECT_CLASS (empathy_chat_parent_class)->finalize (object);
2413 }
2414
2415 static void
2416 chat_constructed (GObject *object)
2417 {
2418         EmpathyChat *chat = EMPATHY_CHAT (object);
2419         EmpathyChatPriv *priv = GET_PRIV (chat);
2420
2421         if (priv->handle_type != TP_HANDLE_TYPE_ROOM)
2422                 chat_add_logs (chat);
2423 #ifndef ENABLE_TPL
2424         /* When async API are involved, pending message are shown at the end of the
2425          * callbacks' chain fired by chat_add_logs */
2426         priv->can_show_pending = TRUE;
2427         show_pending_messages (chat);
2428 #endif /* ENABLE_TPL */
2429 }
2430
2431 static void
2432 empathy_chat_class_init (EmpathyChatClass *klass)
2433 {
2434         GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
2435         GObjectClass   *object_class = G_OBJECT_CLASS (klass);
2436
2437         object_class->finalize = chat_finalize;
2438         object_class->get_property = chat_get_property;
2439         object_class->set_property = chat_set_property;
2440         object_class->constructed = chat_constructed;
2441
2442         widget_class->size_request = chat_size_request;
2443         widget_class->size_allocate = chat_size_allocate;
2444
2445         g_object_class_install_property (object_class,
2446                                          PROP_TP_CHAT,
2447                                          g_param_spec_object ("tp-chat",
2448                                                               "Empathy tp chat",
2449                                                               "The tp chat object",
2450                                                               EMPATHY_TYPE_TP_CHAT,
2451                                                               G_PARAM_CONSTRUCT |
2452                                                               G_PARAM_READWRITE |
2453                                                               G_PARAM_STATIC_STRINGS));
2454         g_object_class_install_property (object_class,
2455                                          PROP_ACCOUNT,
2456                                          g_param_spec_object ("account",
2457                                                               "Account of the chat",
2458                                                               "The account of the chat",
2459                                                               TP_TYPE_ACCOUNT,
2460                                                               G_PARAM_READABLE |
2461                                                               G_PARAM_STATIC_STRINGS));
2462         g_object_class_install_property (object_class,
2463                                          PROP_ID,
2464                                          g_param_spec_string ("id",
2465                                                               "Chat's id",
2466                                                               "The id of the chat",
2467                                                               NULL,
2468                                                               G_PARAM_READABLE |
2469                                                               G_PARAM_STATIC_STRINGS));
2470         g_object_class_install_property (object_class,
2471                                          PROP_NAME,
2472                                          g_param_spec_string ("name",
2473                                                               "Chat's name",
2474                                                               "The name of the chat",
2475                                                               NULL,
2476                                                               G_PARAM_READABLE |
2477                                                               G_PARAM_STATIC_STRINGS));
2478         g_object_class_install_property (object_class,
2479                                          PROP_SUBJECT,
2480                                          g_param_spec_string ("subject",
2481                                                               "Chat's subject",
2482                                                               "The subject or topic of the chat",
2483                                                               NULL,
2484                                                               G_PARAM_READABLE |
2485                                                               G_PARAM_STATIC_STRINGS));
2486         g_object_class_install_property (object_class,
2487                                          PROP_REMOTE_CONTACT,
2488                                          g_param_spec_object ("remote-contact",
2489                                                               "The remote contact",
2490                                                               "The remote contact is any",
2491                                                               EMPATHY_TYPE_CONTACT,
2492                                                               G_PARAM_READABLE |
2493                                                               G_PARAM_STATIC_STRINGS));
2494         g_object_class_install_property (object_class,
2495                                          PROP_SHOW_CONTACTS,
2496                                          g_param_spec_boolean ("show-contacts",
2497                                                                "Contacts' visibility",
2498                                                                "The visibility of the contacts' list",
2499                                                                TRUE,
2500                                                                G_PARAM_READWRITE |
2501                                                                G_PARAM_STATIC_STRINGS));
2502
2503         signals[COMPOSING] =
2504                 g_signal_new ("composing",
2505                               G_OBJECT_CLASS_TYPE (object_class),
2506                               G_SIGNAL_RUN_LAST,
2507                               0,
2508                               NULL, NULL,
2509                               g_cclosure_marshal_VOID__BOOLEAN,
2510                               G_TYPE_NONE,
2511                               1, G_TYPE_BOOLEAN);
2512
2513         signals[NEW_MESSAGE] =
2514                 g_signal_new ("new-message",
2515                               G_OBJECT_CLASS_TYPE (object_class),
2516                               G_SIGNAL_RUN_LAST,
2517                               0,
2518                               NULL, NULL,
2519                               g_cclosure_marshal_VOID__OBJECT,
2520                               G_TYPE_NONE,
2521                               1, EMPATHY_TYPE_MESSAGE);
2522
2523         g_type_class_add_private (object_class, sizeof (EmpathyChatPriv));
2524 }
2525
2526 static gboolean
2527 chat_block_events_timeout_cb (gpointer data)
2528 {
2529         EmpathyChatPriv *priv = GET_PRIV (data);
2530
2531         priv->block_events_timeout_id = 0;
2532
2533         return FALSE;
2534 }
2535
2536 static void
2537 account_manager_prepared_cb (GObject *source_object,
2538                              GAsyncResult *result,
2539                              gpointer user_data)
2540 {
2541         GList *accounts, *l;
2542         TpAccountManager *account_manager = TP_ACCOUNT_MANAGER (source_object);
2543         EmpathyChat *chat = user_data;
2544         GError *error = NULL;
2545
2546         if (!tp_account_manager_prepare_finish (account_manager, result, &error)) {
2547                 DEBUG ("Failed to prepare the account manager: %s", error->message);
2548                 g_error_free (error);
2549                 return;
2550         }
2551
2552         accounts = tp_account_manager_get_valid_accounts (account_manager);
2553
2554         for (l = accounts; l != NULL; l = l->next) {
2555                 TpAccount *account = l->data;
2556                 empathy_signal_connect_weak (account, "status-changed",
2557                                              G_CALLBACK (chat_new_connection_cb),
2558                                              G_OBJECT (chat));
2559         }
2560
2561         g_list_free (accounts);
2562 }
2563
2564 static void
2565 empathy_chat_init (EmpathyChat *chat)
2566 {
2567         EmpathyChatPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chat,
2568                 EMPATHY_TYPE_CHAT, EmpathyChatPriv);
2569
2570         chat->priv = priv;
2571 #ifndef ENABLE_TPL
2572         priv->log_manager = empathy_log_manager_dup_singleton ();
2573 #else
2574         priv->log_manager = tpl_log_manager_dup_singleton ();
2575 #endif /* ENABLE_TPL */
2576         priv->contacts_width = -1;
2577         priv->input_history = NULL;
2578         priv->input_history_current = NULL;
2579         priv->account_manager = tp_account_manager_dup ();
2580
2581         tp_account_manager_prepare_async (priv->account_manager, NULL,
2582                                           account_manager_prepared_cb, chat);
2583
2584         empathy_conf_get_bool (empathy_conf_get (),
2585                                EMPATHY_PREFS_CHAT_SHOW_CONTACTS_IN_ROOMS,
2586                                &priv->show_contacts);
2587
2588         /* Block events for some time to avoid having "has come online" or
2589          * "joined" messages. */
2590         priv->block_events_timeout_id =
2591                 g_timeout_add_seconds (1, chat_block_events_timeout_cb, chat);
2592
2593         /* Add nick name completion */
2594         priv->completion = g_completion_new ((GCompletionFunc) empathy_contact_get_name);
2595         g_completion_set_compare (priv->completion, chat_contacts_completion_func);
2596
2597         chat_create_ui (chat);
2598 }
2599
2600 EmpathyChat *
2601 empathy_chat_new (EmpathyTpChat *tp_chat)
2602 {
2603         return g_object_new (EMPATHY_TYPE_CHAT, "tp-chat", tp_chat, NULL);
2604 }
2605
2606 EmpathyTpChat *
2607 empathy_chat_get_tp_chat (EmpathyChat *chat)
2608 {
2609         EmpathyChatPriv *priv = GET_PRIV (chat);
2610
2611         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2612
2613         return priv->tp_chat;
2614 }
2615
2616 static void display_password_info_bar (EmpathyChat *self,
2617                                        gboolean retry);
2618
2619 static void
2620 provide_password_cb (GObject *tp_chat,
2621                      GAsyncResult *res,
2622                      gpointer user_data)
2623 {
2624         EmpathyChat *self = EMPATHY_CHAT (user_data);
2625         EmpathyChatPriv *priv = GET_PRIV (self);
2626         GError *error = NULL;
2627
2628         if (!empathy_tp_chat_provide_password_finish (EMPATHY_TP_CHAT (tp_chat), res,
2629                                                       &error)) {
2630                 DEBUG ("error: %s", error->message);
2631                 /* FIXME: what should we do if that's another error? Close the channel?
2632                  * Display the raw D-Bus error to the user isn't very useful */
2633                 if (g_error_matches (error, TP_ERRORS, TP_ERROR_AUTHENTICATION_FAILED))
2634                         display_password_info_bar (self, TRUE);
2635                 g_error_free (error);
2636                 return;
2637         }
2638
2639         /* Room joined */
2640         gtk_widget_set_sensitive (priv->hpaned, TRUE);
2641         gtk_widget_grab_focus (self->input_text_view);
2642 }
2643
2644 static void
2645 password_infobar_response_cb (GtkWidget *info_bar,
2646                               gint response_id,
2647                               EmpathyChat *self)
2648 {
2649         EmpathyChatPriv *priv = GET_PRIV (self);
2650         GtkWidget *entry;
2651         const gchar *password;
2652
2653         if (response_id != GTK_RESPONSE_OK)
2654                 goto out;
2655
2656         entry = g_object_get_data (G_OBJECT (info_bar), "password-entry");
2657         g_assert (entry != NULL);
2658
2659         password = gtk_entry_get_text (GTK_ENTRY (entry));
2660
2661         empathy_tp_chat_provide_password_async (priv->tp_chat, password,
2662                                                 provide_password_cb, self);
2663
2664  out:
2665         gtk_widget_destroy (info_bar);
2666 }
2667
2668 static void
2669 password_entry_activate_cb (GtkWidget *entry,
2670                           GtkWidget *info_bar)
2671 {
2672         gtk_info_bar_response (GTK_INFO_BAR (info_bar), GTK_RESPONSE_OK);
2673 }
2674
2675 static void
2676 passwd_join_button_cb (GtkButton *button,
2677                           GtkWidget *info_bar)
2678 {
2679         gtk_info_bar_response (GTK_INFO_BAR (info_bar), GTK_RESPONSE_OK);
2680 }
2681
2682 static void
2683 display_password_info_bar (EmpathyChat *self,
2684                            gboolean retry)
2685 {
2686         EmpathyChatPriv *priv = GET_PRIV (self);
2687         GtkWidget *info_bar;
2688         GtkWidget *content_area;
2689         GtkWidget *hbox;
2690         GtkWidget *image;
2691         GtkWidget *label;
2692         GtkWidget *entry;
2693         GtkWidget *alig;
2694         GtkWidget *button;
2695         GtkMessageType type;
2696         const gchar *msg, *button_label;
2697
2698         if (retry) {
2699                 /* Previous password was wrong */
2700                 type = GTK_MESSAGE_ERROR;
2701                 msg = _("Wrong password; please try again:");
2702                 button_label = _("Retry");
2703         }
2704         else {
2705                 /* First time we're trying to join */
2706                 type = GTK_MESSAGE_QUESTION;
2707                 msg = _("This room is protected by a password:");
2708                 button_label = _("Join");
2709         }
2710
2711         info_bar = gtk_info_bar_new ();
2712         gtk_info_bar_set_message_type (GTK_INFO_BAR (info_bar), type);
2713
2714         content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (info_bar));
2715
2716         hbox = gtk_hbox_new (FALSE, 3);
2717         gtk_container_add (GTK_CONTAINER (content_area), hbox);
2718
2719         /* Add image */
2720         image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_AUTHENTICATION,
2721                                           GTK_ICON_SIZE_DIALOG);
2722         gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
2723
2724         /* Add message */
2725         label = gtk_label_new (msg);
2726         gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);
2727
2728         /* Add password entry */
2729         entry = gtk_entry_new ();
2730         gtk_entry_set_visibility (GTK_ENTRY (entry), FALSE);
2731         gtk_box_pack_start (GTK_BOX (hbox), entry, TRUE, TRUE, 0);
2732
2733         g_signal_connect (entry, "activate",
2734                           G_CALLBACK (password_entry_activate_cb), info_bar);
2735
2736         /* Focus the password entry once it's realized */
2737         g_signal_connect (entry, "realize", G_CALLBACK (gtk_widget_grab_focus), NULL);
2738
2739         /* Add 'Join' button */
2740         alig = gtk_alignment_new (0, 0.5, 0, 0);
2741
2742         button = gtk_button_new_with_label (button_label);
2743         gtk_container_add (GTK_CONTAINER (alig), button);
2744         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
2745
2746         g_signal_connect (button, "clicked", G_CALLBACK (passwd_join_button_cb),
2747                           info_bar);
2748
2749         g_object_set_data (G_OBJECT (info_bar), "password-entry", entry);
2750
2751         gtk_box_pack_start (GTK_BOX (priv->info_bar_vbox), info_bar,
2752                             FALSE, FALSE, 3);
2753         gtk_widget_show_all (hbox);
2754
2755         g_signal_connect (info_bar, "response",
2756                           G_CALLBACK (password_infobar_response_cb), self);
2757
2758         gtk_widget_show_all (info_bar);
2759 }
2760
2761 static void
2762 chat_password_needed_changed_cb (EmpathyChat *self)
2763 {
2764         EmpathyChatPriv *priv = GET_PRIV (self);
2765
2766         if (empathy_tp_chat_password_needed (priv->tp_chat)) {
2767                 display_password_info_bar (self, FALSE);
2768                 gtk_widget_set_sensitive (priv->hpaned, FALSE);
2769         }
2770 }
2771
2772 void
2773 empathy_chat_set_tp_chat (EmpathyChat   *chat,
2774                           EmpathyTpChat *tp_chat)
2775 {
2776         EmpathyChatPriv *priv = GET_PRIV (chat);
2777         TpConnection    *connection;
2778         GPtrArray       *properties;
2779
2780         g_return_if_fail (EMPATHY_IS_CHAT (chat));
2781         g_return_if_fail (EMPATHY_IS_TP_CHAT (tp_chat));
2782         g_return_if_fail (empathy_tp_chat_is_ready (tp_chat));
2783
2784         if (priv->tp_chat) {
2785                 return;
2786         }
2787
2788         if (priv->account) {
2789                 g_object_unref (priv->account);
2790         }
2791
2792         priv->tp_chat = g_object_ref (tp_chat);
2793         connection = empathy_tp_chat_get_connection (priv->tp_chat);
2794         priv->account = g_object_ref (empathy_get_account_for_connection (connection));
2795
2796         g_signal_connect (tp_chat, "destroy",
2797                           G_CALLBACK (chat_destroy_cb),
2798                           chat);
2799         g_signal_connect (tp_chat, "message-received",
2800                           G_CALLBACK (chat_message_received_cb),
2801                           chat);
2802         g_signal_connect (tp_chat, "send-error",
2803                           G_CALLBACK (chat_send_error_cb),
2804                           chat);
2805         g_signal_connect (tp_chat, "chat-state-changed",
2806                           G_CALLBACK (chat_state_changed_cb),
2807                           chat);
2808         g_signal_connect (tp_chat, "property-changed",
2809                           G_CALLBACK (chat_property_changed_cb),
2810                           chat);
2811         g_signal_connect (tp_chat, "members-changed",
2812                           G_CALLBACK (chat_members_changed_cb),
2813                           chat);
2814         g_signal_connect (tp_chat, "member-renamed",
2815                           G_CALLBACK (chat_member_renamed_cb),
2816                           chat);
2817         g_signal_connect_swapped (tp_chat, "notify::remote-contact",
2818                                   G_CALLBACK (chat_remote_contact_changed_cb),
2819                                   chat);
2820         g_signal_connect_swapped (tp_chat, "notify::password-needed",
2821                                   G_CALLBACK (chat_password_needed_changed_cb),
2822                                   chat);
2823
2824         /* Get initial value of properties */
2825         properties = empathy_tp_chat_get_properties (priv->tp_chat);
2826         if (properties != NULL) {
2827                 guint i;
2828
2829                 for (i = 0; i < properties->len; i++) {
2830                         EmpathyTpChatProperty *property;
2831
2832                         property = g_ptr_array_index (properties, i);
2833                         if (property->value == NULL)
2834                                 continue;
2835
2836                         chat_property_changed_cb (priv->tp_chat,
2837                                                   property->name,
2838                                                   property->value,
2839                                                   chat);
2840                 }
2841         }
2842
2843         chat_remote_contact_changed_cb (chat);
2844
2845         if (chat->input_text_view) {
2846                 gtk_widget_set_sensitive (chat->input_text_view, TRUE);
2847                 if (priv->block_events_timeout_id == 0) {
2848                         empathy_chat_view_append_event (chat->view, _("Connected"));
2849                 }
2850         }
2851
2852         g_object_notify (G_OBJECT (chat), "tp-chat");
2853         g_object_notify (G_OBJECT (chat), "id");
2854         g_object_notify (G_OBJECT (chat), "account");
2855
2856         /* This is a noop when tp-chat is set at object construction time and causes
2857          * the pending messages to be show when it's set on the object after it has
2858          * been created */
2859         show_pending_messages (chat);
2860
2861         /* check if a password is needed */
2862         chat_password_needed_changed_cb (chat);
2863 }
2864
2865 TpAccount *
2866 empathy_chat_get_account (EmpathyChat *chat)
2867 {
2868         EmpathyChatPriv *priv = GET_PRIV (chat);
2869
2870         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2871
2872         return priv->account;
2873 }
2874
2875 const gchar *
2876 empathy_chat_get_id (EmpathyChat *chat)
2877 {
2878         EmpathyChatPriv *priv = GET_PRIV (chat);
2879
2880         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2881
2882         return priv->id;
2883 }
2884
2885 const gchar *
2886 empathy_chat_get_name (EmpathyChat *chat)
2887 {
2888         EmpathyChatPriv *priv = GET_PRIV (chat);
2889         const gchar *ret;
2890
2891         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2892
2893         ret = priv->name;
2894         if (!ret && priv->remote_contact) {
2895                 ret = empathy_contact_get_name (priv->remote_contact);
2896         }
2897
2898         if (!ret)
2899                 ret = priv->id;
2900
2901         return ret ? ret : _("Conversation");
2902 }
2903
2904 const gchar *
2905 empathy_chat_get_subject (EmpathyChat *chat)
2906 {
2907         EmpathyChatPriv *priv = GET_PRIV (chat);
2908
2909         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2910
2911         return priv->subject;
2912 }
2913
2914 EmpathyContact *
2915 empathy_chat_get_remote_contact (EmpathyChat *chat)
2916 {
2917         EmpathyChatPriv *priv = GET_PRIV (chat);
2918
2919         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2920
2921         return priv->remote_contact;
2922 }
2923
2924 GtkWidget *
2925 empathy_chat_get_contact_menu (EmpathyChat *chat)
2926 {
2927         EmpathyChatPriv *priv = GET_PRIV (chat);
2928         GtkWidget       *menu = NULL;
2929
2930         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2931
2932         if (priv->remote_contact) {
2933                 menu = empathy_contact_menu_new (priv->remote_contact,
2934                                                  EMPATHY_CONTACT_FEATURE_CALL |
2935                                                  EMPATHY_CONTACT_FEATURE_LOG |
2936                                                  EMPATHY_CONTACT_FEATURE_INFO);
2937         }
2938         else if (priv->contact_list_view) {
2939                 EmpathyContactListView *view;
2940
2941                 view = EMPATHY_CONTACT_LIST_VIEW (priv->contact_list_view);
2942                 menu = empathy_contact_list_view_get_contact_menu (view);
2943         }
2944
2945         return menu;
2946 }
2947
2948 void
2949 empathy_chat_clear (EmpathyChat *chat)
2950 {
2951         g_return_if_fail (EMPATHY_IS_CHAT (chat));
2952
2953         empathy_chat_view_clear (chat->view);
2954 }
2955
2956 void
2957 empathy_chat_scroll_down (EmpathyChat *chat)
2958 {
2959         g_return_if_fail (EMPATHY_IS_CHAT (chat));
2960
2961         empathy_chat_view_scroll_down (chat->view);
2962 }
2963
2964 void
2965 empathy_chat_cut (EmpathyChat *chat)
2966 {
2967         GtkTextBuffer *buffer;
2968
2969         g_return_if_fail (EMPATHY_IS_CHAT (chat));
2970
2971         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2972         if (gtk_text_buffer_get_has_selection (buffer)) {
2973                 GtkClipboard *clipboard;
2974
2975                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
2976
2977                 gtk_text_buffer_cut_clipboard (buffer, clipboard, TRUE);
2978         }
2979 }
2980
2981 void
2982 empathy_chat_copy (EmpathyChat *chat)
2983 {
2984         GtkTextBuffer *buffer;
2985
2986         g_return_if_fail (EMPATHY_IS_CHAT (chat));
2987
2988         if (empathy_chat_view_get_has_selection (chat->view)) {
2989                 empathy_chat_view_copy_clipboard (chat->view);
2990                 return;
2991         }
2992
2993         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2994         if (gtk_text_buffer_get_has_selection (buffer)) {
2995                 GtkClipboard *clipboard;
2996
2997                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
2998
2999                 gtk_text_buffer_copy_clipboard (buffer, clipboard);
3000         }
3001 }
3002
3003 void
3004 empathy_chat_paste (EmpathyChat *chat)
3005 {
3006         GtkTextBuffer *buffer;
3007         GtkClipboard  *clipboard;
3008         EmpathyChatPriv *priv;
3009
3010         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3011
3012         priv = GET_PRIV (chat);
3013
3014         if (priv->tp_chat == NULL ||
3015             !GTK_WIDGET_IS_SENSITIVE (chat->input_text_view))
3016                 return;
3017
3018         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3019         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3020
3021         gtk_text_buffer_paste_clipboard (buffer, clipboard, NULL, TRUE);
3022 }
3023
3024 void
3025 empathy_chat_find (EmpathyChat *chat)
3026 {
3027         EmpathyChatPriv *priv;
3028
3029         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3030
3031         priv = GET_PRIV (chat);
3032
3033         empathy_search_bar_show (EMPATHY_SEARCH_BAR (priv->search_bar));
3034 }
3035
3036 void
3037 empathy_chat_correct_word (EmpathyChat  *chat,
3038                           GtkTextIter *start,
3039                           GtkTextIter *end,
3040                           const gchar *new_word)
3041 {
3042         GtkTextBuffer *buffer;
3043
3044         g_return_if_fail (chat != NULL);
3045         g_return_if_fail (new_word != NULL);
3046
3047         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3048
3049         gtk_text_buffer_delete (buffer, start, end);
3050         gtk_text_buffer_insert (buffer, start,
3051                                 new_word,
3052                                 -1);
3053 }
3054
3055 gboolean
3056 empathy_chat_is_room (EmpathyChat *chat)
3057 {
3058         EmpathyChatPriv *priv = GET_PRIV (chat);
3059
3060         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
3061
3062         return (priv->handle_type == TP_HANDLE_TYPE_ROOM);
3063 }
3064
3065 guint
3066 empathy_chat_get_nb_unread_messages (EmpathyChat *self)
3067 {
3068         EmpathyChatPriv *priv = GET_PRIV (self);
3069
3070         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
3071
3072         return priv->unread_messages;
3073 }
3074
3075 /* called when the messages have been read by user */
3076 void
3077 empathy_chat_messages_read (EmpathyChat *self)
3078 {
3079         EmpathyChatPriv *priv = GET_PRIV (self);
3080
3081         g_return_if_fail (EMPATHY_IS_CHAT (self));
3082
3083         /* FIXME: See Bug#610994, See comments about it in EmpathyChatPriv
3084          * definition. If we are still retrieving the backlogs, do not ACK */
3085         if (priv->retrieving_backlogs)
3086                 return;
3087
3088         if (priv->tp_chat != NULL ) {
3089                         empathy_tp_chat_acknowledge_all_messages (priv->tp_chat);
3090         }
3091         priv->unread_messages = 0;
3092 }