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