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