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