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