empathy-tube-handler: wait that tube is ready before announcing it
[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., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, 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/util.h>
38
39 #include <libempathy/empathy-account-manager.h>
40 #include <libempathy/empathy-log-manager.h>
41 #include <libempathy/empathy-contact-list.h>
42 #include <libempathy/empathy-utils.h>
43 #include <libempathy/empathy-dispatcher.h>
44
45 #include "empathy-chat.h"
46 #include "empathy-conf.h"
47 #include "empathy-spell.h"
48 #include "empathy-spell-dialog.h"
49 #include "empathy-contact-list-store.h"
50 #include "empathy-contact-list-view.h"
51 #include "empathy-contact-menu.h"
52 #include "empathy-theme-manager.h"
53 #include "empathy-smiley-manager.h"
54 #include "empathy-ui-utils.h"
55
56 #define DEBUG_FLAG EMPATHY_DEBUG_CHAT
57 #include <libempathy/empathy-debug.h>
58
59 #define CHAT_DIR_CREATE_MODE  (S_IRUSR | S_IWUSR | S_IXUSR)
60 #define CHAT_FILE_CREATE_MODE (S_IRUSR | S_IWUSR)
61 #define IS_ENTER(v) (v == GDK_Return || v == GDK_ISO_Enter || v == GDK_KP_Enter)
62 #define MAX_INPUT_HEIGHT 150
63 #define COMPOSING_STOP_TIMEOUT 5
64
65 #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyChat)
66 typedef struct {
67         EmpathyTpChat     *tp_chat;
68         gulong            tp_chat_destroy_handler;
69         McAccount         *account;
70         gchar             *id;
71         gchar             *name;
72         gchar             *subject;
73         EmpathyContact    *remote_contact;
74
75         EmpathyLogManager *log_manager;
76         EmpathyAccountManager *account_manager;
77         GSList            *sent_messages;
78         gint               sent_messages_index;
79         GList             *compositors;
80         GCompletion       *completion;
81         guint              composing_stop_timeout_id;
82         guint              block_events_timeout_id;
83         TpHandleType       handle_type;
84         gint               contacts_width;
85         gboolean           has_input_vscroll;
86
87         GtkWidget         *widget;
88         GtkWidget         *hpaned;
89         GtkWidget         *vbox_left;
90         GtkWidget         *scrolled_window_chat;
91         GtkWidget         *scrolled_window_input;
92         GtkWidget         *scrolled_window_contacts;
93         GtkWidget         *hbox_topic;
94         GtkWidget         *label_topic;
95         GtkWidget         *contact_list_view;
96 } EmpathyChatPriv;
97
98 enum {
99         COMPOSING,
100         NEW_MESSAGE,
101         LAST_SIGNAL
102 };
103
104 enum {
105         PROP_0,
106         PROP_TP_CHAT,
107         PROP_ACCOUNT,
108         PROP_ID,
109         PROP_NAME,
110         PROP_SUBJECT,
111         PROP_REMOTE_CONTACT,
112 };
113
114 static guint signals[LAST_SIGNAL] = { 0 };
115
116 G_DEFINE_TYPE (EmpathyChat, empathy_chat, GTK_TYPE_BIN);
117
118 static void
119 chat_get_property (GObject    *object,
120                    guint       param_id,
121                    GValue     *value,
122                    GParamSpec *pspec)
123 {
124         EmpathyChat *chat = EMPATHY_CHAT (object);
125         EmpathyChatPriv *priv = GET_PRIV (object);
126
127         switch (param_id) {
128         case PROP_TP_CHAT:
129                 g_value_set_object (value, priv->tp_chat);
130                 break;
131         case PROP_ACCOUNT:
132                 g_value_set_object (value, priv->account);
133                 break;
134         case PROP_NAME:
135                 g_value_set_string (value, empathy_chat_get_name (chat));
136                 break;
137         case PROP_ID:
138                 g_value_set_string (value, priv->id);
139                 break;
140         case PROP_SUBJECT:
141                 g_value_set_string (value, priv->subject);
142                 break;
143         case PROP_REMOTE_CONTACT:
144                 g_value_set_object (value, priv->remote_contact);
145                 break;
146         default:
147                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
148                 break;
149         };
150 }
151
152 static void
153 chat_set_property (GObject      *object,
154                    guint         param_id,
155                    const GValue *value,
156                    GParamSpec   *pspec)
157 {
158         EmpathyChat *chat = EMPATHY_CHAT (object);
159
160         switch (param_id) {
161         case PROP_TP_CHAT:
162                 empathy_chat_set_tp_chat (chat, EMPATHY_TP_CHAT (g_value_get_object (value)));
163                 break;
164         default:
165                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
166                 break;
167         };
168 }
169
170 static void
171 chat_connect_channel_reconnected (EmpathyDispatchOperation *dispatch,
172                                   const GError             *error,
173                                   gpointer                  user_data)
174 {
175         EmpathyChat *chat = EMPATHY_CHAT (user_data);
176         EmpathyTpChat *tpchat;
177
178         if (error != NULL) {
179                 empathy_chat_view_append_event (chat->view,
180                         _("Failed to reconnect this chat"));
181                 return;
182         }
183
184         tpchat = EMPATHY_TP_CHAT (
185                 empathy_dispatch_operation_get_channel_wrapper (dispatch));
186
187         if (empathy_dispatch_operation_claim (dispatch)) {
188                 empathy_chat_set_tp_chat (chat, tpchat);
189         }
190 }
191
192 static void
193 chat_connection_changed_cb (EmpathyAccountManager *manager,
194                             McAccount *account,
195                             TpConnectionStatusReason reason,
196                             TpConnectionStatus current,
197                             TpConnectionStatus previous,
198                             EmpathyChat *chat)
199 {
200         EmpathyChatPriv *priv = GET_PRIV (chat);
201
202         if (current == TP_CONNECTION_STATUS_CONNECTED && !priv->tp_chat &&
203             empathy_account_equal (account, priv->account) &&
204             priv->handle_type != TP_HANDLE_TYPE_NONE &&
205             !EMP_STR_EMPTY (priv->id)) {
206                 
207                 DEBUG ("Account reconnected, request a new Text channel");
208
209                 switch (priv->handle_type) {
210                         case TP_HANDLE_TYPE_CONTACT:
211                                 empathy_dispatcher_chat_with_contact_id (account, priv->id,
212                                         chat_connect_channel_reconnected,
213                                         chat);
214                                 break;
215                         case TP_HANDLE_TYPE_ROOM:
216                                 empathy_dispatcher_join_muc (account, priv->id,
217                                         chat_connect_channel_reconnected,
218                                         chat);
219                                 break;
220                         default:
221                                 g_assert_not_reached ();
222                                 break;
223                 }
224         }
225 }
226
227 static void
228 chat_composing_remove_timeout (EmpathyChat *chat)
229 {
230         EmpathyChatPriv *priv;
231
232         priv = GET_PRIV (chat);
233
234         if (priv->composing_stop_timeout_id) {
235                 g_source_remove (priv->composing_stop_timeout_id);
236                 priv->composing_stop_timeout_id = 0;
237         }
238 }
239
240 static gboolean
241 chat_composing_stop_timeout_cb (EmpathyChat *chat)
242 {
243         EmpathyChatPriv *priv;
244
245         priv = GET_PRIV (chat);
246
247         priv->composing_stop_timeout_id = 0;
248         empathy_tp_chat_set_state (priv->tp_chat,
249                                    TP_CHANNEL_CHAT_STATE_PAUSED);
250
251         return FALSE;
252 }
253
254 static void
255 chat_composing_start (EmpathyChat *chat)
256 {
257         EmpathyChatPriv *priv;
258
259         priv = GET_PRIV (chat);
260
261         if (priv->composing_stop_timeout_id) {
262                 /* Just restart the timeout */
263                 chat_composing_remove_timeout (chat);
264         } else {
265                 empathy_tp_chat_set_state (priv->tp_chat,
266                                            TP_CHANNEL_CHAT_STATE_COMPOSING);
267         }
268
269         priv->composing_stop_timeout_id = g_timeout_add_seconds (
270                 COMPOSING_STOP_TIMEOUT,
271                 (GSourceFunc) chat_composing_stop_timeout_cb,
272                 chat);
273 }
274
275 static void
276 chat_composing_stop (EmpathyChat *chat)
277 {
278         EmpathyChatPriv *priv;
279
280         priv = GET_PRIV (chat);
281
282         chat_composing_remove_timeout (chat);
283         empathy_tp_chat_set_state (priv->tp_chat,
284                                    TP_CHANNEL_CHAT_STATE_ACTIVE);
285 }
286
287 static void 
288 chat_sent_message_add (EmpathyChat  *chat,
289                        const gchar *str)
290 {
291         EmpathyChatPriv *priv;
292         GSList         *list;
293         GSList         *item;
294
295         priv = GET_PRIV (chat);
296
297         /* Save the sent message in our repeat buffer */
298         list = priv->sent_messages;
299         
300         /* Remove any other occurances of this msg */
301         while ((item = g_slist_find_custom (list, str, (GCompareFunc) strcmp)) != NULL) {
302                 list = g_slist_remove_link (list, item);
303                 g_free (item->data);
304                 g_slist_free1 (item);
305         }
306
307         /* Trim the list to the last 10 items */
308         while (g_slist_length (list) > 10) {
309                 item = g_slist_last (list);
310                 if (item) {
311                         list = g_slist_remove_link (list, item);
312                         g_free (item->data);
313                         g_slist_free1 (item);
314                 }
315         }
316
317         /* Add new message */
318         list = g_slist_prepend (list, g_strdup (str));
319
320         /* Set list and reset the index */
321         priv->sent_messages = list;
322         priv->sent_messages_index = -1;
323 }
324
325 static const gchar *
326 chat_sent_message_get_next (EmpathyChat *chat)
327 {
328         EmpathyChatPriv *priv;
329         gint            max;
330         
331         priv = GET_PRIV (chat);
332
333         if (!priv->sent_messages) {
334                 DEBUG ("No sent messages, next message is NULL");
335                 return NULL;
336         }
337
338         max = g_slist_length (priv->sent_messages) - 1;
339
340         if (priv->sent_messages_index < max) {
341                 priv->sent_messages_index++;
342         }
343         
344         DEBUG ("Returning next message index:%d", priv->sent_messages_index);
345
346         return g_slist_nth_data (priv->sent_messages, priv->sent_messages_index);
347 }
348
349 static const gchar *
350 chat_sent_message_get_last (EmpathyChat *chat)
351 {
352         EmpathyChatPriv *priv;
353
354         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
355
356         priv = GET_PRIV (chat);
357         
358         if (!priv->sent_messages) {
359                 DEBUG ("No sent messages, last message is NULL");
360                 return NULL;
361         }
362
363         if (priv->sent_messages_index >= 0) {
364                 priv->sent_messages_index--;
365         }
366
367         DEBUG ("Returning last message index:%d", priv->sent_messages_index);
368
369         return g_slist_nth_data (priv->sent_messages, priv->sent_messages_index);
370 }
371
372 static void
373 chat_send (EmpathyChat  *chat,
374            const gchar *msg)
375 {
376         EmpathyChatPriv *priv;
377         EmpathyMessage  *message;
378
379         if (EMP_STR_EMPTY (msg)) {
380                 return;
381         }
382
383         priv = GET_PRIV (chat);
384
385         chat_sent_message_add (chat, msg);
386
387         if (g_str_has_prefix (msg, "/clear")) {
388                 empathy_chat_view_clear (chat->view);
389                 return;
390         }
391
392         /* Blacklist messages begining by '/', except for "/me" and "/say"
393          * because they are handled in EmpathyMessage */
394         if (msg[0] == '/' &&
395             !g_str_has_prefix (msg, "/me") &&
396             !g_str_has_prefix (msg, "/say")) {
397                 empathy_chat_view_append_event (chat->view,
398                         _("Unsupported command"));
399                 return;
400         }
401
402         /* We can send the message */
403         message = empathy_message_new (msg);
404         empathy_tp_chat_send (priv->tp_chat, message);
405         g_object_unref (message);
406 }
407
408 static void
409 chat_input_text_view_send (EmpathyChat *chat)
410 {
411         EmpathyChatPriv *priv;
412         GtkTextBuffer  *buffer;
413         GtkTextIter     start, end;
414         gchar          *msg;
415
416         priv = GET_PRIV (chat);
417
418         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
419
420         gtk_text_buffer_get_bounds (buffer, &start, &end);
421         msg = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
422
423         /* clear the input field */
424         gtk_text_buffer_set_text (buffer, "", -1);
425
426         chat_send (chat, msg);
427         g_free (msg);
428 }
429
430 static void
431 chat_state_changed_cb (EmpathyTpChat      *tp_chat,
432                        EmpathyContact     *contact,
433                        TpChannelChatState  state,
434                        EmpathyChat        *chat)
435 {
436         EmpathyChatPriv *priv;
437         GList          *l;
438         gboolean        was_composing;
439
440         priv = GET_PRIV (chat);
441
442         if (empathy_contact_is_user (contact)) {
443                 /* We don't care about our own chat state */
444                 return;
445         }
446
447         was_composing = (priv->compositors != NULL);
448
449         /* Find the contact in the list. After that l is the list elem or NULL */
450         for (l = priv->compositors; l; l = l->next) {
451                 if (contact == l->data) {
452                         break;
453                 }
454         }
455
456         switch (state) {
457         case TP_CHANNEL_CHAT_STATE_GONE:
458         case TP_CHANNEL_CHAT_STATE_INACTIVE:
459         case TP_CHANNEL_CHAT_STATE_PAUSED:
460         case TP_CHANNEL_CHAT_STATE_ACTIVE:
461                 /* Contact is not composing */
462                 if (l) {
463                         priv->compositors = g_list_remove_link (priv->compositors, l);
464                         g_object_unref (l->data);
465                         g_list_free1 (l);
466                 }
467                 break;
468         case TP_CHANNEL_CHAT_STATE_COMPOSING:
469                 /* Contact is composing */
470                 if (!l) {
471                         priv->compositors = g_list_prepend (priv->compositors,
472                                                             g_object_ref (contact));
473                 }
474                 break;
475         default:
476                 g_assert_not_reached ();
477         }
478
479         DEBUG ("Was composing: %s now composing: %s",
480                 was_composing ? "yes" : "no",
481                 priv->compositors ? "yes" : "no");
482
483         if ((was_composing && !priv->compositors) ||
484             (!was_composing && priv->compositors)) {
485                 /* Composing state changed */
486                 g_signal_emit (chat, signals[COMPOSING], 0,
487                                priv->compositors != NULL);
488         }
489 }
490
491 static void
492 chat_message_received (EmpathyChat *chat, EmpathyMessage *message)
493 {
494         EmpathyChatPriv *priv = GET_PRIV (chat);
495         EmpathyContact  *sender;
496
497         sender = empathy_message_get_sender (message);
498
499         DEBUG ("Appending new message from %s (%d)",
500                 empathy_contact_get_name (sender),
501                 empathy_contact_get_handle (sender));
502
503         empathy_chat_view_append_message (chat->view, message);
504
505         /* We received a message so the contact is no longer composing */
506         chat_state_changed_cb (priv->tp_chat, sender,
507                                TP_CHANNEL_CHAT_STATE_ACTIVE,
508                                chat);
509
510         g_signal_emit (chat, signals[NEW_MESSAGE], 0, message);
511 }
512
513 static void
514 chat_message_received_cb (EmpathyTpChat  *tp_chat,
515                           EmpathyMessage *message,
516                           EmpathyChat    *chat)
517 {
518         chat_message_received (chat, message);
519         empathy_tp_chat_acknowledge_message (tp_chat, message);
520 }
521
522 static void
523 chat_send_error_cb (EmpathyTpChat          *tp_chat,
524                     EmpathyMessage         *message,
525                     TpChannelTextSendError  error_code,
526                     EmpathyChat            *chat)
527 {
528         const gchar *error;
529         gchar       *str;
530
531         switch (error_code) {
532         case TP_CHANNEL_TEXT_SEND_ERROR_OFFLINE:
533                 error = _("offline");
534                 break;
535         case TP_CHANNEL_TEXT_SEND_ERROR_INVALID_CONTACT:
536                 error = _("invalid contact");
537                 break;
538         case TP_CHANNEL_TEXT_SEND_ERROR_PERMISSION_DENIED:
539                 error = _("permission denied");
540                 break;
541         case TP_CHANNEL_TEXT_SEND_ERROR_TOO_LONG:
542                 error = _("too long message");
543                 break;
544         case TP_CHANNEL_TEXT_SEND_ERROR_NOT_IMPLEMENTED:
545                 error = _("not implemented");
546                 break;
547         default:
548                 error = _("unknown");
549                 break;
550         }
551
552         str = g_strdup_printf (_("Error sending message '%s': %s"),
553                                empathy_message_get_body (message),
554                                error);
555         empathy_chat_view_append_event (chat->view, str);
556         g_free (str);
557 }
558
559 static void
560 chat_property_changed_cb (EmpathyTpChat *tp_chat,
561                           const gchar   *name,
562                           GValue        *value,
563                           EmpathyChat   *chat)
564 {
565         EmpathyChatPriv *priv = GET_PRIV (chat);
566
567         if (!tp_strdiff (name, "subject")) {
568                 g_free (priv->subject);
569                 priv->subject = g_value_dup_string (value);
570                 g_object_notify (G_OBJECT (chat), "subject");
571
572                 if (EMP_STR_EMPTY (priv->subject)) {
573                         gtk_widget_hide (priv->hbox_topic);
574                 } else {
575                         gtk_label_set_text (GTK_LABEL (priv->label_topic), priv->subject);
576                         gtk_widget_show (priv->hbox_topic);
577                 }
578                 if (priv->block_events_timeout_id == 0) {
579                         gchar *str;
580
581                         if (!EMP_STR_EMPTY (priv->subject)) {
582                                 str = g_strdup_printf (_("Topic set to: %s"), priv->subject);
583                         } else {
584                                 str = g_strdup (_("No topic defined"));
585                         }
586                         empathy_chat_view_append_event (EMPATHY_CHAT (chat)->view, str);
587                         g_free (str);
588                 }
589         }
590         else if (!tp_strdiff (name, "name")) {
591                 g_free (priv->name);
592                 priv->name = g_value_dup_string (value);
593                 g_object_notify (G_OBJECT (chat), "name");
594         }
595 }
596
597 static void
598 chat_input_text_buffer_changed_cb (GtkTextBuffer *buffer,
599                                    EmpathyChat    *chat)
600 {
601         EmpathyChatPriv *priv;
602         GtkTextIter     start, end;
603         gchar          *str;
604         gboolean        spell_checker = FALSE;
605
606         priv = GET_PRIV (chat);
607
608         if (gtk_text_buffer_get_char_count (buffer) == 0) {
609                 chat_composing_stop (chat);
610         } else {
611                 chat_composing_start (chat);
612         }
613
614         empathy_conf_get_bool (empathy_conf_get (),
615                               EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED,
616                               &spell_checker);
617
618         gtk_text_buffer_get_start_iter (buffer, &start);
619
620         if (!spell_checker) {
621                 gtk_text_buffer_get_end_iter (buffer, &end);
622                 gtk_text_buffer_remove_tag_by_name (buffer, "misspelled", &start, &end);
623                 return;
624         }
625
626         if (!empathy_spell_supported ()) {
627                 return;
628         }
629
630         /* NOTE: this is really inefficient, we shouldn't have to
631            reiterate the whole buffer each time and check each work
632            every time. */
633         while (TRUE) {
634                 gboolean correct = FALSE;
635
636                 /* if at start */
637                 if (gtk_text_iter_is_start (&start)) {
638                         end = start;
639
640                         if (!gtk_text_iter_forward_word_end (&end)) {
641                                 /* no whole word yet */
642                                 break;
643                         }
644                 } else {
645                         if (!gtk_text_iter_forward_word_end (&end)) {
646                                 /* must be the end of the buffer */
647                                 break;
648                         }
649
650                         start = end;
651                         gtk_text_iter_backward_word_start (&start);
652                 }
653
654                 str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
655
656                 /* spell check string if not a command */
657                 if (str[0] != '/') {
658                         correct = empathy_spell_check (str);
659                 } else {
660                         correct = TRUE;
661                 }
662
663                 if (!correct) {
664                         gtk_text_buffer_apply_tag_by_name (buffer, "misspelled", &start, &end);
665                 } else {
666                         gtk_text_buffer_remove_tag_by_name (buffer, "misspelled", &start, &end);
667                 }
668
669                 g_free (str);
670
671                 /* set start iter to the end iters position */
672                 start = end;
673         }
674 }
675
676 static gboolean
677 chat_input_key_press_event_cb (GtkWidget   *widget,
678                                GdkEventKey *event,
679                                EmpathyChat *chat)
680 {
681         EmpathyChatPriv *priv;
682         GtkAdjustment  *adj;
683         gdouble         val;
684         GtkWidget      *text_view_sw;
685
686         priv = GET_PRIV (chat);
687
688         /* Catch ctrl+up/down so we can traverse messages we sent */
689         if ((event->state & GDK_CONTROL_MASK) && 
690             (event->keyval == GDK_Up || 
691              event->keyval == GDK_Down)) {
692                 GtkTextBuffer *buffer;
693                 const gchar   *str;
694
695                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
696
697                 if (event->keyval == GDK_Up) {
698                         str = chat_sent_message_get_next (chat);
699                 } else {
700                         str = chat_sent_message_get_last (chat);
701                 }
702
703                 g_signal_handlers_block_by_func (buffer, 
704                                                  chat_input_text_buffer_changed_cb,
705                                                  chat);
706                 gtk_text_buffer_set_text (buffer, str ? str : "", -1);
707                 g_signal_handlers_unblock_by_func (buffer, 
708                                                    chat_input_text_buffer_changed_cb,
709                                                    chat);
710
711                 return TRUE;    
712         }
713
714         /* Catch enter but not ctrl/shift-enter */
715         if (IS_ENTER (event->keyval) &&
716             !(event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
717                 GtkTextView *view;
718
719                 /* This is to make sure that kinput2 gets the enter. And if
720                  * it's handled there we shouldn't send on it. This is because
721                  * kinput2 uses Enter to commit letters. See:
722                  * http://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=104299
723                  */
724
725                 view = GTK_TEXT_VIEW (chat->input_text_view);
726                 if (gtk_im_context_filter_keypress (view->im_context, event)) {
727                         GTK_TEXT_VIEW (chat->input_text_view)->need_im_reset = TRUE;
728                         return TRUE;
729                 }
730
731                 chat_input_text_view_send (chat);
732                 return TRUE;
733         }
734
735         text_view_sw = gtk_widget_get_parent (GTK_WIDGET (chat->view));
736
737         if (IS_ENTER (event->keyval) &&
738             (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
739                 /* Newline for shift/control-enter. */
740                 return FALSE;
741         }
742         if (!(event->state & GDK_CONTROL_MASK) &&
743             event->keyval == GDK_Page_Up) {
744                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
745                 gtk_adjustment_set_value (adj, adj->value - adj->page_size);
746                 return TRUE;
747         }
748         if ((event->state & GDK_CONTROL_MASK) != GDK_CONTROL_MASK &&
749             event->keyval == GDK_Page_Down) {
750                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
751                 val = MIN (adj->value + adj->page_size, adj->upper - adj->page_size);
752                 gtk_adjustment_set_value (adj, val);
753                 return TRUE;
754         }
755         if (!(event->state & (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) &&
756             event->keyval == GDK_Tab) {
757                 GtkTextBuffer *buffer;
758                 GtkTextIter    start, current;
759                 gchar         *nick, *completed;
760                 GList         *list, *completed_list;
761                 gboolean       is_start_of_buffer;
762
763                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (EMPATHY_CHAT (chat)->input_text_view));
764                 gtk_text_buffer_get_iter_at_mark (buffer, &current, gtk_text_buffer_get_insert (buffer));
765
766                 /* Get the start of the nick to complete. */
767                 gtk_text_buffer_get_iter_at_mark (buffer, &start, gtk_text_buffer_get_insert (buffer));
768                 gtk_text_iter_backward_word_start (&start);
769                 is_start_of_buffer = gtk_text_iter_is_start (&start);
770
771                 list = empathy_contact_list_get_members (EMPATHY_CONTACT_LIST (priv->tp_chat));
772                 g_completion_add_items (priv->completion, list);
773
774                 nick = gtk_text_buffer_get_text (buffer, &start, &current, FALSE);
775                 completed_list = g_completion_complete (priv->completion,
776                                                         nick,
777                                                         &completed);
778
779                 g_free (nick);
780
781                 if (completed) {
782                         guint        len;
783                         const gchar *text;
784                         gchar       *complete_char = NULL;
785
786                         gtk_text_buffer_delete (buffer, &start, &current);
787
788                         len = g_list_length (completed_list);
789
790                         if (len == 1) {
791                                 /* If we only have one hit, use that text
792                                  * instead of the text in completed since the
793                                  * completed text will use the typed string
794                                  * which might be cased all wrong.
795                                  * Fixes #120876
796                                  * */
797                                 text = empathy_contact_get_name (completed_list->data);
798                         } else {
799                                 text = completed;
800                         }
801
802                         gtk_text_buffer_insert_at_cursor (buffer, text, strlen (text));
803
804                         if (len == 1 && is_start_of_buffer &&
805                             empathy_conf_get_string (empathy_conf_get (),
806                                                      EMPATHY_PREFS_CHAT_NICK_COMPLETION_CHAR,
807                                                      &complete_char) &&
808                             complete_char != NULL) {
809                                 gtk_text_buffer_insert_at_cursor (buffer,
810                                                                   complete_char,
811                                                                   strlen (complete_char));
812                                 gtk_text_buffer_insert_at_cursor (buffer, " ", 1);
813                                 g_free (complete_char);
814                         }
815
816                         g_free (completed);
817                 }
818
819                 g_completion_clear_items (priv->completion);
820
821                 g_list_foreach (list, (GFunc) g_object_unref, NULL);
822                 g_list_free (list);
823
824                 return TRUE;
825         }
826
827         return FALSE;
828 }
829
830 static gboolean
831 chat_text_view_focus_in_event_cb (GtkWidget  *widget,
832                                   GdkEvent   *event,
833                                   EmpathyChat *chat)
834 {
835         gtk_widget_grab_focus (chat->input_text_view);
836
837         return TRUE;
838 }
839
840 static gboolean
841 chat_input_set_size_request_idle (gpointer sw)
842 {
843         gtk_widget_set_size_request (sw, -1, MAX_INPUT_HEIGHT);
844
845         return FALSE;
846 }
847
848 static void
849 chat_input_size_request_cb (GtkWidget      *widget,
850                             GtkRequisition *requisition,
851                             EmpathyChat    *chat)
852 {
853         EmpathyChatPriv *priv = GET_PRIV (chat);
854         GtkWidget       *sw;
855
856         sw = gtk_widget_get_parent (widget);
857         if (requisition->height >= MAX_INPUT_HEIGHT && !priv->has_input_vscroll) {
858                 g_idle_add (chat_input_set_size_request_idle, sw);
859                 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw),
860                                                 GTK_POLICY_NEVER,
861                                                 GTK_POLICY_ALWAYS);
862                 priv->has_input_vscroll = TRUE;
863         }
864
865         if (requisition->height < MAX_INPUT_HEIGHT && priv->has_input_vscroll) {
866                 gtk_widget_set_size_request (sw, -1, -1);
867                 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw),
868                                                 GTK_POLICY_NEVER,
869                                                 GTK_POLICY_NEVER);
870                 priv->has_input_vscroll = FALSE;
871         }
872 }
873
874 static void
875 chat_input_realize_cb (GtkWidget   *widget,
876                        EmpathyChat *chat)
877 {
878         DEBUG ("Setting focus to the input text view");
879         gtk_widget_grab_focus (widget);
880 }
881
882 static void
883 chat_insert_smiley_activate_cb (EmpathySmileyManager *manager,
884                                 EmpathySmiley        *smiley,
885                                 gpointer              user_data)
886 {
887         EmpathyChat   *chat = EMPATHY_CHAT (user_data);
888         GtkTextBuffer *buffer;
889         GtkTextIter    iter;
890
891         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
892
893         gtk_text_buffer_get_end_iter (buffer, &iter);
894         gtk_text_buffer_insert (buffer, &iter, smiley->str, -1);
895
896         gtk_text_buffer_get_end_iter (buffer, &iter);
897         gtk_text_buffer_insert (buffer, &iter, " ", -1);
898 }
899
900 typedef struct {
901         EmpathyChat  *chat;
902         gchar       *word;
903
904         GtkTextIter  start;
905         GtkTextIter  end;
906 } EmpathyChatSpell;
907
908 static EmpathyChatSpell *
909 chat_spell_new (EmpathyChat  *chat,
910                 const gchar *word,
911                 GtkTextIter  start,
912                 GtkTextIter  end)
913 {
914         EmpathyChatSpell *chat_spell;
915
916         chat_spell = g_slice_new0 (EmpathyChatSpell);
917
918         chat_spell->chat = g_object_ref (chat);
919         chat_spell->word = g_strdup (word);
920         chat_spell->start = start;
921         chat_spell->end = end;
922
923         return chat_spell;
924 }
925
926 static void
927 chat_spell_free (EmpathyChatSpell *chat_spell)
928 {
929         g_object_unref (chat_spell->chat);
930         g_free (chat_spell->word);
931         g_slice_free (EmpathyChatSpell, chat_spell);
932 }
933
934 static void
935 chat_text_check_word_spelling_cb (GtkMenuItem     *menuitem,
936                                   EmpathyChatSpell *chat_spell)
937 {
938         empathy_spell_dialog_show (chat_spell->chat,
939                                   &chat_spell->start,
940                                   &chat_spell->end,
941                                   chat_spell->word);
942 }
943
944 static void
945 chat_text_send_cb (GtkMenuItem *menuitem,
946                    EmpathyChat *chat)
947 {
948         chat_input_text_view_send (chat);
949 }
950
951 static void
952 chat_input_populate_popup_cb (GtkTextView *view,
953                               GtkMenu     *menu,
954                               EmpathyChat *chat)
955 {
956         EmpathyChatPriv      *priv;
957         GtkTextBuffer        *buffer;
958         GtkTextTagTable      *table;
959         GtkTextTag           *tag;
960         gint                  x, y;
961         GtkTextIter           iter, start, end;
962         GtkWidget            *item;
963         gchar                *str = NULL;
964         EmpathyChatSpell      *chat_spell;
965         EmpathySmileyManager *smiley_manager;
966         GtkWidget            *smiley_menu;
967         GtkWidget            *image;
968
969         priv = GET_PRIV (chat);
970         buffer = gtk_text_view_get_buffer (view);
971
972         /* Add the emoticon menu. */
973         item = gtk_separator_menu_item_new ();
974         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
975         gtk_widget_show (item);
976
977         item = gtk_image_menu_item_new_with_mnemonic (_("Insert Smiley"));
978         image = gtk_image_new_from_icon_name ("face-smile",
979                                               GTK_ICON_SIZE_MENU);
980         gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
981         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
982         gtk_widget_show (item);
983
984         smiley_manager = empathy_smiley_manager_dup_singleton ();
985         smiley_menu = empathy_smiley_menu_new (smiley_manager,
986                                                chat_insert_smiley_activate_cb,
987                                                chat);
988         gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), smiley_menu);
989         g_object_unref (smiley_manager);
990
991         /* Add the Send menu item. */
992         gtk_text_buffer_get_bounds (buffer, &start, &end);
993         str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
994         if (!EMP_STR_EMPTY (str)) {
995                 item = gtk_menu_item_new_with_mnemonic (_("_Send"));
996                 g_signal_connect (G_OBJECT (item), "activate",
997                                   G_CALLBACK (chat_text_send_cb), chat);
998                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
999                 gtk_widget_show (item);
1000         }
1001         str = NULL;
1002
1003         /* Add the spell check menu item. */
1004         table = gtk_text_buffer_get_tag_table (buffer);
1005         tag = gtk_text_tag_table_lookup (table, "misspelled");
1006         gtk_widget_get_pointer (GTK_WIDGET (view), &x, &y);
1007         gtk_text_view_window_to_buffer_coords (GTK_TEXT_VIEW (view),
1008                                                GTK_TEXT_WINDOW_WIDGET,
1009                                                x, y,
1010                                                &x, &y);
1011         gtk_text_view_get_iter_at_location (GTK_TEXT_VIEW (view), &iter, x, y);
1012         start = end = iter;
1013         if (gtk_text_iter_backward_to_tag_toggle (&start, tag) &&
1014             gtk_text_iter_forward_to_tag_toggle (&end, tag)) {
1015
1016                 str = gtk_text_buffer_get_text (buffer,
1017                                                 &start, &end, FALSE);
1018         }
1019         if (!EMP_STR_EMPTY (str)) {
1020                 chat_spell = chat_spell_new (chat, str, start, end);
1021                 g_object_set_data_full (G_OBJECT (menu),
1022                                         "chat_spell", chat_spell,
1023                                         (GDestroyNotify) chat_spell_free);
1024
1025                 item = gtk_separator_menu_item_new ();
1026                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1027                 gtk_widget_show (item);
1028
1029                 item = gtk_image_menu_item_new_with_mnemonic (_("_Check Word Spelling..."));
1030                 image = gtk_image_new_from_icon_name (GTK_STOCK_SPELL_CHECK,
1031                                                       GTK_ICON_SIZE_MENU);
1032                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
1033                 g_signal_connect (item,
1034                                   "activate",
1035                                   G_CALLBACK (chat_text_check_word_spelling_cb),
1036                                   chat_spell);
1037                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1038                 gtk_widget_show (item);
1039         }
1040 }
1041
1042 static gboolean
1043 chat_log_filter (EmpathyMessage *message,
1044                  gpointer user_data)
1045 {
1046         EmpathyChat *chat = (EmpathyChat *) user_data;
1047         EmpathyChatPriv *priv = GET_PRIV (chat);
1048         const GList *pending;
1049
1050         pending = empathy_tp_chat_get_pending_messages (priv->tp_chat);
1051
1052         for (; pending; pending = g_list_next (pending)) {
1053                 if (empathy_message_equal (message, pending->data)) {
1054                         return FALSE;
1055                 }
1056         }
1057
1058         return TRUE;
1059 }
1060
1061 static void
1062 chat_add_logs (EmpathyChat *chat)
1063 {
1064         EmpathyChatPriv *priv = GET_PRIV (chat);
1065         gboolean         is_chatroom;
1066         GList           *messages, *l;
1067
1068         if (!priv->id) {
1069                 return;
1070         }
1071
1072         /* Turn off scrolling temporarily */
1073         empathy_chat_view_scroll (chat->view, FALSE);
1074
1075         /* Add messages from last conversation */
1076         is_chatroom = priv->handle_type == TP_HANDLE_TYPE_ROOM;
1077
1078         messages = empathy_log_manager_get_filtered_messages (priv->log_manager,
1079                                                               priv->account,
1080                                                               priv->id,
1081                                                               is_chatroom,
1082                                                               5,
1083                                                               chat_log_filter,
1084                                                               chat);
1085
1086         for (l = messages; l; l = g_list_next (l)) {
1087                 empathy_chat_view_append_message (chat->view, l->data);
1088                 g_object_unref (l->data);
1089         }
1090
1091         g_list_free (messages);
1092
1093         /* Turn back on scrolling */
1094         empathy_chat_view_scroll (chat->view, TRUE);
1095 }
1096
1097 static gint
1098 chat_contacts_completion_func (const gchar *s1,
1099                                const gchar *s2,
1100                                gsize        n)
1101 {
1102         gchar *tmp, *nick1, *nick2;
1103         gint   ret;
1104
1105         if (s1 == s2) {
1106                 return 0;
1107         }
1108         if (!s1 || !s2) {
1109                 return s1 ? -1 : +1;
1110         }
1111
1112         tmp = g_utf8_normalize (s1, -1, G_NORMALIZE_DEFAULT);
1113         nick1 = g_utf8_casefold (tmp, -1);
1114         g_free (tmp);
1115
1116         tmp = g_utf8_normalize (s2, -1, G_NORMALIZE_DEFAULT);
1117         nick2 = g_utf8_casefold (tmp, -1);
1118         g_free (tmp);
1119
1120         ret = strncmp (nick1, nick2, n);
1121
1122         g_free (nick1);
1123         g_free (nick2);
1124
1125         return ret;
1126 }
1127
1128 static void
1129 chat_members_changed_cb (EmpathyTpChat  *tp_chat,
1130                          EmpathyContact *contact,
1131                          EmpathyContact *actor,
1132                          guint           reason,
1133                          gchar          *message,
1134                          gboolean        is_member,
1135                          EmpathyChat    *chat)
1136 {
1137         EmpathyChatPriv *priv = GET_PRIV (chat);
1138
1139         if (priv->block_events_timeout_id == 0) {
1140                 gchar *str;
1141
1142                 empathy_contact_run_until_ready (contact,
1143                                                  EMPATHY_CONTACT_READY_NAME,
1144                                                  NULL);
1145
1146                 if (is_member) {
1147                         str = g_strdup_printf (_("%s has joined the room"),
1148                                                empathy_contact_get_name (contact));
1149                 } else {
1150                         str = g_strdup_printf (_("%s has left the room"),
1151                                                empathy_contact_get_name (contact));
1152                 }
1153                 empathy_chat_view_append_event (chat->view, str);
1154                 g_free (str);
1155         }
1156 }
1157
1158 static gboolean
1159 chat_reset_size_request (gpointer widget)
1160 {
1161         gtk_widget_set_size_request (widget, -1, -1);
1162
1163         return FALSE;
1164 }
1165
1166 static void
1167 chat_set_show_contacts (EmpathyChat *chat, gboolean show)
1168 {
1169         EmpathyChatPriv *priv = GET_PRIV (chat);
1170
1171         if (!priv->scrolled_window_contacts) {
1172                 return;
1173         }
1174
1175         if (show) {
1176                 EmpathyContactListStore *store;
1177                 gint                     min_width;
1178
1179                 /* We are adding the contact list to the chat, we don't want the
1180                  * chat view to become too small. If the chat view is already
1181                  * smaller than 250 make sure that size won't change. If the
1182                  * chat view is bigger the contact list will take some space on
1183                  * it but we make sure the chat view don't become smaller than
1184                  * 250. Relax the size request once the resize is done */
1185                 min_width = MIN (priv->vbox_left->allocation.width, 250);
1186                 gtk_widget_set_size_request (priv->vbox_left, min_width, -1);
1187                 g_idle_add (chat_reset_size_request, priv->vbox_left);
1188
1189                 if (priv->contacts_width > 0) {
1190                         gtk_paned_set_position (GTK_PANED (priv->hpaned),
1191                                                 priv->contacts_width);
1192                 }
1193
1194                 store = empathy_contact_list_store_new (EMPATHY_CONTACT_LIST (priv->tp_chat));
1195                 priv->contact_list_view = GTK_WIDGET (empathy_contact_list_view_new (store,
1196                         EMPATHY_CONTACT_LIST_FEATURE_NONE,
1197                         EMPATHY_CONTACT_FEATURE_CHAT |
1198                         EMPATHY_CONTACT_FEATURE_CALL |
1199                         EMPATHY_CONTACT_FEATURE_LOG |
1200                         EMPATHY_CONTACT_FEATURE_INFO));
1201                 gtk_container_add (GTK_CONTAINER (priv->scrolled_window_contacts),
1202                                    priv->contact_list_view);
1203                 gtk_widget_show (priv->contact_list_view);
1204                 gtk_widget_show (priv->scrolled_window_contacts);
1205                 g_object_unref (store);
1206         } else {
1207                 priv->contacts_width = gtk_paned_get_position (GTK_PANED (priv->hpaned));
1208                 gtk_widget_hide (priv->scrolled_window_contacts);
1209                 if (priv->contact_list_view) {
1210                         gtk_widget_destroy (priv->contact_list_view);
1211                         priv->contact_list_view = NULL;
1212                 }
1213         }
1214 }
1215
1216 static void
1217 chat_remote_contact_changed_cb (EmpathyChat *chat)
1218 {
1219         EmpathyChatPriv *priv = GET_PRIV (chat);
1220
1221         if (priv->remote_contact) {
1222                 g_object_unref (priv->remote_contact);
1223                 priv->remote_contact = NULL;
1224         }
1225
1226         priv->remote_contact = empathy_tp_chat_get_remote_contact (priv->tp_chat);
1227         if (priv->remote_contact) {
1228                 g_object_ref (priv->remote_contact);
1229                 priv->handle_type = TP_HANDLE_TYPE_CONTACT;
1230                 g_free (priv->id);
1231                 priv->id = g_strdup (empathy_contact_get_id (priv->remote_contact));
1232         }
1233         else if (priv->tp_chat) {
1234                 TpChannel *channel;
1235
1236                 channel = empathy_tp_chat_get_channel (priv->tp_chat);
1237                 g_object_get (channel, "handle-type", &priv->handle_type, NULL);
1238                 g_free (priv->id);
1239                 priv->id = g_strdup (empathy_tp_chat_get_id (priv->tp_chat));
1240         }
1241
1242         chat_set_show_contacts (chat, priv->remote_contact == NULL);
1243
1244         g_object_notify (G_OBJECT (chat), "remote-contact");
1245         g_object_notify (G_OBJECT (chat), "id");
1246 }
1247
1248 static void
1249 chat_destroy_cb (EmpathyTpChat *tp_chat,
1250                  EmpathyChat   *chat)
1251 {
1252         EmpathyChatPriv *priv;
1253
1254         priv = GET_PRIV (chat);
1255
1256         if (!priv->tp_chat) {
1257                 return;
1258         }
1259
1260         chat_composing_remove_timeout (chat);
1261         g_object_unref (priv->tp_chat);
1262         priv->tp_chat = NULL;
1263         g_object_notify (G_OBJECT (chat), "tp-chat");
1264
1265         empathy_chat_view_append_event (chat->view, _("Disconnected"));
1266         gtk_widget_set_sensitive (chat->input_text_view, FALSE);
1267         chat_set_show_contacts (chat, FALSE);
1268 }
1269
1270 static void
1271 show_pending_messages (EmpathyChat *chat) {
1272         EmpathyChatPriv *priv = GET_PRIV (chat);
1273         const GList *messages, *l;
1274
1275         if (chat->view == NULL || priv->tp_chat == NULL)
1276                 return;
1277
1278         messages = empathy_tp_chat_get_pending_messages (priv->tp_chat);
1279
1280         for (l = messages; l != NULL ; l = g_list_next (l)) {
1281                 EmpathyMessage *message = EMPATHY_MESSAGE (l->data);
1282                 chat_message_received (chat, message);
1283         }
1284         empathy_tp_chat_acknowledge_messages (priv->tp_chat, messages);
1285 }
1286
1287 static void
1288 chat_create_ui (EmpathyChat *chat)
1289 {
1290         EmpathyChatPriv *priv = GET_PRIV (chat);
1291         GtkBuilder      *gui;
1292         GList           *list = NULL; 
1293         gchar           *filename;
1294         GtkTextBuffer   *buffer;
1295
1296         filename = empathy_file_lookup ("empathy-chat.ui",
1297                                         "libempathy-gtk");
1298         gui = empathy_builder_get_file (filename,
1299                                         "chat_widget", &priv->widget,
1300                                         "hpaned", &priv->hpaned,
1301                                         "vbox_left", &priv->vbox_left,
1302                                         "scrolled_window_chat", &priv->scrolled_window_chat,
1303                                         "scrolled_window_input", &priv->scrolled_window_input,
1304                                         "hbox_topic", &priv->hbox_topic,
1305                                         "label_topic", &priv->label_topic,
1306                                         "scrolled_window_contacts", &priv->scrolled_window_contacts,
1307                                         NULL);
1308         g_free (filename);
1309
1310         /* Add message view. */
1311         chat->view = empathy_theme_manager_create_view (empathy_theme_manager_get ());
1312         g_signal_connect (chat->view, "focus_in_event",
1313                           G_CALLBACK (chat_text_view_focus_in_event_cb),
1314                           chat);
1315         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_chat),
1316                            GTK_WIDGET (chat->view));
1317         gtk_widget_show (GTK_WIDGET (chat->view));
1318
1319         /* Add input GtkTextView */
1320         chat->input_text_view = g_object_new (GTK_TYPE_TEXT_VIEW,
1321                                               "pixels-above-lines", 2,
1322                                               "pixels-below-lines", 2,
1323                                               "pixels-inside-wrap", 1,
1324                                               "right-margin", 2,
1325                                               "left-margin", 2,
1326                                               "wrap-mode", GTK_WRAP_WORD_CHAR,
1327                                               NULL);
1328         g_signal_connect (chat->input_text_view, "key-press-event",
1329                           G_CALLBACK (chat_input_key_press_event_cb),
1330                           chat);
1331         g_signal_connect (chat->input_text_view, "size-request",
1332                           G_CALLBACK (chat_input_size_request_cb),
1333                           chat);
1334         g_signal_connect (chat->input_text_view, "realize",
1335                           G_CALLBACK (chat_input_realize_cb),
1336                           chat);
1337         g_signal_connect (chat->input_text_view, "populate-popup",
1338                           G_CALLBACK (chat_input_populate_popup_cb),
1339                           chat);
1340         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1341         g_signal_connect (buffer, "changed",
1342                           G_CALLBACK (chat_input_text_buffer_changed_cb),
1343                           chat);
1344         gtk_text_buffer_create_tag (buffer, "misspelled",
1345                                     "underline", PANGO_UNDERLINE_ERROR,
1346                                     NULL);
1347         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_input),
1348                            chat->input_text_view);
1349         gtk_widget_show (chat->input_text_view);
1350
1351         /* Create contact list */
1352         chat_set_show_contacts (chat, priv->remote_contact == NULL);
1353
1354         /* Initialy hide the topic, will be shown if not empty */
1355         gtk_widget_hide (priv->hbox_topic);
1356
1357         /* Set widget focus order */
1358         list = g_list_append (NULL, priv->scrolled_window_input);
1359         gtk_container_set_focus_chain (GTK_CONTAINER (priv->vbox_left), list);
1360         g_list_free (list);
1361
1362         list = g_list_append (NULL, priv->vbox_left);
1363         list = g_list_append (list, priv->scrolled_window_contacts);
1364         gtk_container_set_focus_chain (GTK_CONTAINER (priv->hpaned), list);
1365         g_list_free (list);
1366
1367         list = g_list_append (NULL, priv->hpaned);
1368         list = g_list_append (list, priv->hbox_topic);
1369         gtk_container_set_focus_chain (GTK_CONTAINER (priv->widget), list);
1370         g_list_free (list);
1371
1372         /* Add the main widget in the chat widget */
1373         gtk_container_add (GTK_CONTAINER (chat), priv->widget);
1374         g_object_unref (gui);
1375 }
1376
1377 static void
1378 chat_size_request (GtkWidget      *widget,
1379                    GtkRequisition *requisition)
1380 {
1381   GtkBin *bin = GTK_BIN (widget);
1382
1383   requisition->width = GTK_CONTAINER (widget)->border_width * 2;
1384   requisition->height = GTK_CONTAINER (widget)->border_width * 2;
1385
1386   if (bin->child && GTK_WIDGET_VISIBLE (bin->child))
1387     {
1388       GtkRequisition child_requisition;
1389       
1390       gtk_widget_size_request (bin->child, &child_requisition);
1391
1392       requisition->width += child_requisition.width;
1393       requisition->height += child_requisition.height;
1394     }
1395 }
1396
1397 static void
1398 chat_size_allocate (GtkWidget     *widget,
1399                     GtkAllocation *allocation)
1400 {
1401   GtkBin *bin = GTK_BIN (widget);
1402   GtkAllocation child_allocation;
1403   
1404   widget->allocation = *allocation;
1405
1406   if (bin->child && GTK_WIDGET_VISIBLE (bin->child))
1407     {
1408       child_allocation.x = allocation->x + GTK_CONTAINER (widget)->border_width;
1409       child_allocation.y = allocation->y + GTK_CONTAINER (widget)->border_width;
1410       child_allocation.width = MAX (allocation->width - GTK_CONTAINER (widget)->border_width * 2, 0);
1411       child_allocation.height = MAX (allocation->height - GTK_CONTAINER (widget)->border_width * 2, 0);
1412
1413       gtk_widget_size_allocate (bin->child, &child_allocation);
1414     }
1415 }
1416
1417 static void
1418 chat_finalize (GObject *object)
1419 {
1420         EmpathyChat     *chat;
1421         EmpathyChatPriv *priv;
1422
1423         chat = EMPATHY_CHAT (object);
1424         priv = GET_PRIV (chat);
1425
1426         DEBUG ("Finalized: %p", object);
1427
1428         g_slist_foreach (priv->sent_messages, (GFunc) g_free, NULL);
1429         g_slist_free (priv->sent_messages);
1430
1431         g_list_foreach (priv->compositors, (GFunc) g_object_unref, NULL);
1432         g_list_free (priv->compositors);
1433
1434         chat_composing_remove_timeout (chat);
1435
1436         g_signal_handlers_disconnect_by_func (priv->account_manager,
1437                                               chat_connection_changed_cb, object);
1438
1439         g_object_unref (priv->account_manager);
1440         g_object_unref (priv->log_manager);
1441
1442         if (priv->tp_chat) {
1443                 g_signal_handler_disconnect (priv->tp_chat, priv->tp_chat_destroy_handler);
1444                 empathy_tp_chat_close (priv->tp_chat);
1445                 g_object_unref (priv->tp_chat);
1446         }
1447         if (priv->account) {
1448                 g_object_unref (priv->account);
1449         }
1450         if (priv->remote_contact) {
1451                 g_object_unref (priv->remote_contact);
1452         }
1453
1454         if (priv->block_events_timeout_id) {
1455                 g_source_remove (priv->block_events_timeout_id);
1456         }
1457
1458         g_free (priv->id);
1459         g_free (priv->name);
1460         g_free (priv->subject);
1461         g_completion_free (priv->completion);
1462
1463         G_OBJECT_CLASS (empathy_chat_parent_class)->finalize (object);
1464 }
1465
1466 static void
1467 chat_constructed (GObject *object)
1468 {
1469         EmpathyChat *chat = EMPATHY_CHAT (object);
1470
1471         chat_create_ui (chat);
1472         chat_add_logs (chat);
1473         show_pending_messages (chat);
1474 }
1475
1476 static void
1477 empathy_chat_class_init (EmpathyChatClass *klass)
1478 {
1479         GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
1480         GObjectClass   *object_class = G_OBJECT_CLASS (klass);
1481
1482         object_class->finalize = chat_finalize;
1483         object_class->get_property = chat_get_property;
1484         object_class->set_property = chat_set_property;
1485         object_class->constructed = chat_constructed;
1486
1487         widget_class->size_request = chat_size_request;
1488         widget_class->size_allocate = chat_size_allocate;
1489
1490         g_object_class_install_property (object_class,
1491                                          PROP_TP_CHAT,
1492                                          g_param_spec_object ("tp-chat",
1493                                                               "Empathy tp chat",
1494                                                               "The tp chat object",
1495                                                               EMPATHY_TYPE_TP_CHAT,
1496                                                               G_PARAM_CONSTRUCT |
1497                                                               G_PARAM_READWRITE));
1498         g_object_class_install_property (object_class,
1499                                          PROP_ACCOUNT,
1500                                          g_param_spec_object ("account",
1501                                                               "Account of the chat",
1502                                                               "The account of the chat",
1503                                                               MC_TYPE_ACCOUNT,
1504                                                               G_PARAM_READABLE));
1505         g_object_class_install_property (object_class,
1506                                          PROP_ID,
1507                                          g_param_spec_string ("id",
1508                                                               "Chat's id",
1509                                                               "The id of the chat",
1510                                                               NULL,
1511                                                               G_PARAM_READABLE));
1512         g_object_class_install_property (object_class,
1513                                          PROP_NAME,
1514                                          g_param_spec_string ("name",
1515                                                               "Chat's name",
1516                                                               "The name of the chat",
1517                                                               NULL,
1518                                                               G_PARAM_READABLE));
1519         g_object_class_install_property (object_class,
1520                                          PROP_SUBJECT,
1521                                          g_param_spec_string ("subject",
1522                                                               "Chat's subject",
1523                                                               "The subject or topic of the chat",
1524                                                               NULL,
1525                                                               G_PARAM_READABLE));
1526         g_object_class_install_property (object_class,
1527                                          PROP_REMOTE_CONTACT,
1528                                          g_param_spec_object ("remote-contact",
1529                                                               "The remote contact",
1530                                                               "The remote contact is any",
1531                                                               EMPATHY_TYPE_CONTACT,
1532                                                               G_PARAM_READABLE));
1533
1534         signals[COMPOSING] =
1535                 g_signal_new ("composing",
1536                               G_OBJECT_CLASS_TYPE (object_class),
1537                               G_SIGNAL_RUN_LAST,
1538                               0,
1539                               NULL, NULL,
1540                               g_cclosure_marshal_VOID__BOOLEAN,
1541                               G_TYPE_NONE,
1542                               1, G_TYPE_BOOLEAN);
1543
1544         signals[NEW_MESSAGE] =
1545                 g_signal_new ("new-message",
1546                               G_OBJECT_CLASS_TYPE (object_class),
1547                               G_SIGNAL_RUN_LAST,
1548                               0,
1549                               NULL, NULL,
1550                               g_cclosure_marshal_VOID__OBJECT,
1551                               G_TYPE_NONE,
1552                               1, EMPATHY_TYPE_MESSAGE);
1553
1554         g_type_class_add_private (object_class, sizeof (EmpathyChatPriv));
1555 }
1556
1557 static gboolean
1558 chat_block_events_timeout_cb (gpointer data)
1559 {
1560         EmpathyChatPriv *priv = GET_PRIV (data);
1561
1562         priv->block_events_timeout_id = 0;
1563
1564         return FALSE;
1565 }
1566
1567 static void
1568 empathy_chat_init (EmpathyChat *chat)
1569 {
1570         EmpathyChatPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chat,
1571                 EMPATHY_TYPE_CHAT, EmpathyChatPriv);
1572
1573         chat->priv = priv;
1574         priv->log_manager = empathy_log_manager_dup_singleton ();
1575         priv->contacts_width = -1;
1576         priv->sent_messages = NULL;
1577         priv->sent_messages_index = -1;
1578         priv->account_manager = empathy_account_manager_dup_singleton ();
1579
1580         g_signal_connect (priv->account_manager,
1581                           "account-connection-changed",
1582                           G_CALLBACK (chat_connection_changed_cb),
1583                           chat);
1584
1585         /* Block events for some time to avoid having "has come online" or
1586          * "joined" messages. */
1587         priv->block_events_timeout_id =
1588                 g_timeout_add_seconds (1, chat_block_events_timeout_cb, chat);
1589
1590         /* Add nick name completion */
1591         priv->completion = g_completion_new ((GCompletionFunc) empathy_contact_get_name);
1592         g_completion_set_compare (priv->completion, chat_contacts_completion_func);
1593 }
1594
1595 EmpathyChat *
1596 empathy_chat_new (EmpathyTpChat *tp_chat)
1597 {
1598         return g_object_new (EMPATHY_TYPE_CHAT, "tp-chat", tp_chat, NULL);
1599 }
1600
1601 EmpathyTpChat *
1602 empathy_chat_get_tp_chat (EmpathyChat *chat)
1603 {
1604         EmpathyChatPriv *priv = GET_PRIV (chat);
1605
1606         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
1607
1608         return priv->tp_chat;
1609 }
1610
1611 void
1612 empathy_chat_set_tp_chat (EmpathyChat   *chat,
1613                           EmpathyTpChat *tp_chat)
1614 {
1615         EmpathyChatPriv *priv = GET_PRIV (chat);
1616
1617         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1618         g_return_if_fail (EMPATHY_IS_TP_CHAT (tp_chat));
1619         g_return_if_fail (empathy_tp_chat_is_ready (tp_chat));
1620
1621         if (priv->tp_chat) {
1622                 return;
1623         }
1624
1625         if (priv->account) {
1626                 g_object_unref (priv->account);
1627         }
1628
1629         priv->tp_chat = g_object_ref (tp_chat);
1630         priv->account = g_object_ref (empathy_tp_chat_get_account (tp_chat));
1631
1632         g_signal_connect (tp_chat, "message-received",
1633                           G_CALLBACK (chat_message_received_cb),
1634                           chat);
1635         g_signal_connect (tp_chat, "send-error",
1636                           G_CALLBACK (chat_send_error_cb),
1637                           chat);
1638         g_signal_connect (tp_chat, "chat-state-changed",
1639                           G_CALLBACK (chat_state_changed_cb),
1640                           chat);
1641         g_signal_connect (tp_chat, "property-changed",
1642                           G_CALLBACK (chat_property_changed_cb),
1643                           chat);
1644         g_signal_connect (tp_chat, "members-changed",
1645                           G_CALLBACK (chat_members_changed_cb),
1646                           chat);
1647         g_signal_connect_swapped (tp_chat, "notify::remote-contact",
1648                                   G_CALLBACK (chat_remote_contact_changed_cb),
1649                                   chat);
1650         priv->tp_chat_destroy_handler =
1651                 g_signal_connect (tp_chat, "destroy",
1652                           G_CALLBACK (chat_destroy_cb),
1653                           chat);
1654
1655         chat_remote_contact_changed_cb (chat);
1656
1657         if (chat->input_text_view) {
1658                 gtk_widget_set_sensitive (chat->input_text_view, TRUE);
1659                 if (priv->block_events_timeout_id == 0) {
1660                         empathy_chat_view_append_event (chat->view, _("Connected"));
1661                 }
1662         }
1663
1664         g_object_notify (G_OBJECT (chat), "tp-chat");
1665         g_object_notify (G_OBJECT (chat), "id");
1666         g_object_notify (G_OBJECT (chat), "account");
1667
1668         /* This is a noop when tp-chat is set at object construction time and causes
1669          * the pending messages to be show when it's set on the object after it has
1670          * been created */
1671         show_pending_messages (chat);
1672 }
1673
1674 McAccount *
1675 empathy_chat_get_account (EmpathyChat *chat)
1676 {
1677         EmpathyChatPriv *priv = GET_PRIV (chat);
1678
1679         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
1680
1681         return priv->account;
1682 }
1683
1684 const gchar *
1685 empathy_chat_get_id (EmpathyChat *chat)
1686 {
1687         EmpathyChatPriv *priv = GET_PRIV (chat);
1688
1689         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
1690
1691         return priv->id;
1692 }
1693
1694 const gchar *
1695 empathy_chat_get_name (EmpathyChat *chat)
1696 {
1697         EmpathyChatPriv *priv = GET_PRIV (chat);
1698         const gchar *ret;
1699
1700         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
1701
1702         ret = priv->name;
1703         if (!ret && priv->remote_contact) {
1704                 ret = empathy_contact_get_name (priv->remote_contact);
1705         }
1706
1707         if (!ret)
1708                 ret = priv->id;
1709
1710         return ret ? ret : _("Conversation");
1711 }
1712
1713 const gchar *
1714 empathy_chat_get_subject (EmpathyChat *chat)
1715 {
1716         EmpathyChatPriv *priv = GET_PRIV (chat);
1717
1718         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
1719
1720         return priv->subject;
1721 }
1722
1723 EmpathyContact *
1724 empathy_chat_get_remote_contact (EmpathyChat *chat)
1725 {
1726         EmpathyChatPriv *priv = GET_PRIV (chat);
1727
1728         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
1729
1730         return priv->remote_contact;
1731 }
1732
1733 guint
1734 empathy_chat_get_members_count (EmpathyChat *chat)
1735 {
1736         EmpathyChatPriv *priv = GET_PRIV (chat);
1737
1738         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), 0);
1739
1740         if (priv->tp_chat) {
1741                 return empathy_tp_chat_get_members_count (priv->tp_chat);
1742         }
1743
1744         return 0;
1745 }
1746
1747 GtkWidget *
1748 empathy_chat_get_contact_menu (EmpathyChat *chat)
1749 {
1750         EmpathyChatPriv *priv = GET_PRIV (chat);
1751         GtkWidget       *menu = NULL;
1752
1753         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
1754
1755         if (priv->remote_contact) {
1756                 menu = empathy_contact_menu_new (priv->remote_contact,
1757                                                  EMPATHY_CONTACT_FEATURE_CALL |
1758                                                  EMPATHY_CONTACT_FEATURE_LOG |
1759                                                  EMPATHY_CONTACT_FEATURE_INFO);
1760         }
1761         else if (priv->contact_list_view) {
1762                 EmpathyContactListView *view;
1763
1764                 view = EMPATHY_CONTACT_LIST_VIEW (priv->contact_list_view);
1765                 menu = empathy_contact_list_view_get_contact_menu (view);
1766         }
1767
1768         return menu;
1769 }
1770
1771 void
1772 empathy_chat_clear (EmpathyChat *chat)
1773 {
1774         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1775
1776         empathy_chat_view_clear (chat->view);
1777 }
1778
1779 void
1780 empathy_chat_scroll_down (EmpathyChat *chat)
1781 {
1782         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1783
1784         empathy_chat_view_scroll_down (chat->view);
1785 }
1786
1787 void
1788 empathy_chat_cut (EmpathyChat *chat)
1789 {
1790         GtkTextBuffer *buffer;
1791
1792         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1793
1794         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1795         if (gtk_text_buffer_get_has_selection (buffer)) {
1796                 GtkClipboard *clipboard;
1797
1798                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
1799
1800                 gtk_text_buffer_cut_clipboard (buffer, clipboard, TRUE);
1801         }
1802 }
1803
1804 void
1805 empathy_chat_copy (EmpathyChat *chat)
1806 {
1807         GtkTextBuffer *buffer;
1808
1809         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1810
1811         if (empathy_chat_view_get_has_selection (chat->view)) {
1812                 empathy_chat_view_copy_clipboard (chat->view);
1813                 return;
1814         }
1815
1816         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1817         if (gtk_text_buffer_get_has_selection (buffer)) {
1818                 GtkClipboard *clipboard;
1819
1820                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
1821
1822                 gtk_text_buffer_copy_clipboard (buffer, clipboard);
1823         }
1824 }
1825
1826 void
1827 empathy_chat_paste (EmpathyChat *chat)
1828 {
1829         GtkTextBuffer *buffer;
1830         GtkClipboard  *clipboard;
1831
1832         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1833
1834         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1835         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
1836
1837         gtk_text_buffer_paste_clipboard (buffer, clipboard, NULL, TRUE);
1838 }
1839
1840 void
1841 empathy_chat_correct_word (EmpathyChat  *chat,
1842                           GtkTextIter *start,
1843                           GtkTextIter *end,
1844                           const gchar *new_word)
1845 {
1846         GtkTextBuffer *buffer;
1847
1848         g_return_if_fail (chat != NULL);
1849         g_return_if_fail (new_word != NULL);
1850
1851         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1852
1853         gtk_text_buffer_delete (buffer, start, end);
1854         gtk_text_buffer_insert (buffer, start,
1855                                 new_word,
1856                                 -1);
1857 }
1858
1859 gboolean
1860 empathy_chat_is_room (EmpathyChat *chat)
1861 {
1862         EmpathyChatPriv *priv = GET_PRIV (chat);
1863
1864         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
1865
1866         return (priv->handle_type == TP_HANDLE_TYPE_ROOM);
1867 }
1868