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