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