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