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